简体   繁体   English

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

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

I'm making a random file generator that makes a txt with random cartesian points the problem is: when I use the String.format to a number (let's say 4.3), I get "4,3". 我正在制作一个随机文件生成器,该文件生成器使用随机的笛卡尔点表示txt,问题是:当我将String.format用作数字时(比如说4.3),我得到“ 4,3”。 But I don't want the comma, I don't even know why it makes a comma, there's no use to it at all... The code: 但是我不想要逗号,我什至不知道为什么会产生逗号,根本没有用...代码:

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();

I've solved the problem using replace(",", "."), but I kinda think this is not a good solution, and I want to know if there's any reason to have a comma in the format method. 我已经使用replace(“,”,“。”)解决了问题,但是我有点认为这不是一个好的解决方案,并且我想知道是否有任何理由在format方法中使用逗号。

Instead of using a workaround (replace the comma by a dot) you should solve it in a proper way. 代替使用替代方法(用逗号代替逗号),应以适当的方式解决它。 "There is an API for that." “有一个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);

produced output 生产的产出

pt_BR = 1,4
en_GB = 1.4

And it's not a nonstandardized function (see the Javadoc) . 而且它不是nonstandardized function (请参阅Javadoc) Standard is use the default locale and if needed you are able to change the behavior . 标准是use the default locale ,如果需要, you are able to change the behavior

Try this: 尝试这个:

        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);

The output : 输出 :

33.1 -37.7

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

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