繁体   English   中英

String.format返回使用逗号作为分隔符的双精度型

[英]String.format returning a double that uses comma as separator

我正在制作一个随机文件生成器,该文件生成器使用随机的笛卡尔点表示txt,问题是:当我将String.format用作数字时(比如说4.3),我得到“ 4,3”。 但是我不想要逗号,我什至不知道为什么会产生逗号,根本没有用...代码:

FileWriter fileWriter = new FileWriter(new File("txt.txt"));
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
Random generator = new Random();
int nPoints = generator.nextInt(10)+10;
bufferedWriter.write(""+nPoints);
for (int n=0; n<nPoints; n++){
    bufferedWriter.newLine();
    String x = String.format("%.1f", generator.nextDouble()*100-50);
    String y = String.format("%.1f", generator.nextDouble()*100-50);
    bufferedWriter.write(x + " " + y);
}
bufferedWriter.close();

我已经使用replace(“,”,“。”)解决了问题,但是我有点认为这不是一个好的解决方案,并且我想知道是否有任何理由在format方法中使用逗号。

代替使用替代方法(用逗号代替逗号),应以适当的方式解决它。 “有一个API。”

Locale.setDefault(new Locale("pt", "BR"));
String portuguese = String.format("%.1f", 1.4d);
String english = String.format(Locale.ENGLISH, "%.1f", 1.4d);
System.out.println("pt_BR = " + portuguese);
System.out.println("en_GB = " + english);

生产的产出

pt_BR = 1,4
en_GB = 1.4

而且它不是nonstandardized function (请参阅Javadoc) 标准是use the default locale ,如果需要, you are able to change the behavior

尝试这个:

        DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.getDefault());
        otherSymbols.setDecimalSeparator('.');
        DecimalFormat formatter = new DecimalFormat("####.0",otherSymbols);

        for (int n=0; n<nPoints; n++){
            bufferedWriter.newLine();
            String x = formatter.format(generator.nextDouble()*100-50);
            String y = formatter.format(generator.nextDouble()*100-50);

输出 :

33.1 -37.7

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM