【问题标题】:DecimalFormat("0.0") returns data with a comma as separator instead of a point [duplicate]DecimalFormat("0.0") 返回以逗号而不是点作为分隔符的数据[重复]
【发布时间】:2022-01-11 23:48:51
【问题描述】:
import java.text.DecimalFormat;

public class FormatTest {
     public static void main(String[] args) {
        DecimalFormat df = new DecimalFormat("0.0");

        System.out.println(df.format(10.4));  // prints 10,4 instead of 10.4
        System.out.println(df.format(100.5)); // prints 100,5 instead of 100.5
        System.out.println(df.format(3000.3));// prints 3000,3 instead of 3000.3
    }
}

我上面的代码的输出如下,用逗号作为小数分隔符,而通常它应该是一个点。我使用带有 Maven 的 NetBeans 12.5。

Java 似乎使用我的本地小数分隔符而不是点。另外,我需要强制点 (".") 作为唯一的分隔符。

--- exec-maven-plugin:3.0.0:exec (default-cli) @ FormatTest ---

10,4

100,5

3000,3

【问题讨论】:

    标签: java decimalformat


    【解决方案1】:

    您可以(并且您实际上需要避免本地化)主动配置DecimalFormat,详细信息如下:

    public class Main {
        public static void main(String[] args) throws Exception {
            DecimalFormat df = new DecimalFormat("0.0");
            DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols();
            decimalFormatSymbols.setDecimalSeparator('.');
            df.setDecimalFormatSymbols(decimalFormatSymbols);
            
            System.out.println(df.format(10.4));  // prints 10,4 instead of 10.4
            System.out.println(df.format(100.5)); // prints 100,5 instead of 100.5
            System.out.println(df.format(3000.3));// prints 3000,3 instead of 3000.3
        }
    }
    

    您可以在reference documentation中阅读更多详细信息,其中可以阅读重要的sn-p:

    特殊模式字符

    (...)

    使用了此处列出的字符 在非本地化模式中。本地化模式使用相应的 取自此格式化程序的 DecimalFormatSymbols 对象的字符 相反,这些角色失去了他们的特殊地位。

    【讨论】:

      【解决方案2】:

      您可以像 post 那样更改十进制格式

      NumberFormat nf = NumberFormat.getNumberInstance(Locale.GERMAN);
      DecimalFormat df = (DecimalFormat)nf;
      

      【讨论】:

      • 事实上,在我的代码中,我在同一个链接上使用了一个解决方案,使用 .replace(',', '.') 但我认为可以有更好的东西(但使用 DecimalFormat 同样短) .
      猜你喜欢
      • 2017-09-30
      • 2015-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多