gpt4 book ai didi

java - 需要帮助对整数进行一些特定的格式化(java)

转载 作者:行者123 更新时间:2023-11-29 05:46:57 25 4
gpt4 key购买 nike

好吧,我正在制作一个广播节目,目前广播频率是整数,例如; 107900、87900。

我需要将这样的数字转换成这样的字符串,

107.9, 87.9

我一直在尝试使用 DecimalFormat,但没有取得任何成功。感谢任何提示或提示!

这是我尝试过的一些东西,

frequency = 107900;
double newFreq = frequency / 1000;
String name = String.valueOf(newFreq);
result = 107.0

double freqer = 107900/1000;
DecimalFormat dec = new DecimalFormat("#.0");
result = 107.0

int frequency = 107900;
DecimalFormat dec = new DecimalFormat("#.0");
result = 107900.0

谢谢!

最佳答案

为了不混淆 float ,并假设它们都是小数点后的一位数字(无论如何这里都有广播电台),您可以使用:

String.format ("%d.%d", freq / 1000, (freq / 100) % 10)

例如,请参阅以下完整程序:

public class Test {
static String radStat (int freq) {
return String.format ("%d.%d", freq / 1000, (freq / 100) % 10);
}

public static void main(String args[]) {
System.out.println("107900 -> " + radStat (107900));
System.out.println(" 87900 -> " + radStat ( 87900));
System.out.println("101700 -> " + radStat (101700));
}
}

哪些输出:

107900 -> 107.9
87900 -> 87.9
101700 -> 101.7

关于java - 需要帮助对整数进行一些特定的格式化(java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15513877/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com