java - 创建没有小数分隔符的小数

标签 java decimalformat

我正在尝试接收一个 int,它始终是一个带 2 位小数的数字。 例如:

  • 1000 是 10,00(我的小数点分隔符是逗号)。
  • 100 是 1,00
  • 0 是 0,00
  • 100099 是 1.000,99

所以我尽量避免使用字符串运算符,而是使用具有模式 0,00 和德语语言环境的 DecimalFormat。

但是当我得到 10004 时,我得到的输出是 1.00.04

这是我的代码:

public static String formatDecimal(double number) {
    //String pattern  = "#,00";
    String pattern  = "0,00";
    DecimalFormat fN = (DecimalFormat) NumberFormat.getNumberInstance(Locale.GERMAN);
    fN.applyPattern(pattern); 

    return fN.format(number)
}

最佳答案

为什么要使用自己的模式? Java 默认实现在大多数语言环境中都有很好的模式。至少通过查看 Oracle's docs 它看起来应该做你需要做的事情:

Locale                  Formatted Numbers
German (Germany)        123.456,789
German (Switzerland)    123'456.789
English (United States) 123,456.789

因此,您需要做的(除了将数字除以 100 之外)将最小小数位数设置为“2”:

public static String formatDecimal(double number) {
    NumberFormat german = NumberFormat.getNumberInstance(Locale.GERMAN);
    german.setMinimumFractionDigits(2);
    return german.format(number / 100);
}

已编辑:按预期打印数字:

0,00
0,01
0,02
0,09
0,10
0,11
0,99
1,00
1,01
9,99
10,00
10,01
99,99
100,00
100,01
999,99
1.000,00
1.000,01
9.999,99
10.000,00
10.000,01
99.999,99
100.000,00
100.000,01
999.999,99
1.000.000,00
1.000.000,01

关于java - 创建没有小数分隔符的小数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34685712/

相关文章:

java - 在 Android 中的 Fragment 中绘图

java - 在 Windows 集群上部署 Java Service Fabric 应用程序失败 - 无 jFabricRuntime

java.lang.IllegalArgumentException 十进制格式

java - decimalFormat 保存为 double

java - 从图库中选择图像时未获得正确的路径

java - Google API v3 通过传递文件夹名称检查存在的文件夹

Javafx Textfield - getText() 为空?

java - 为什么德语本地化的 DecimalFormat 在 Java 中成功地将 "3.2"解析为十进制?

Java:如何从某个字符串位置解析 double 并获取其后面的 char 的位置?

java - DecimalFormat 在 Oracle Java 1.7 和 IBM java 1.6 中给出不同的结果