【问题标题】:String.format returning a double that uses comma as separatorString.format 返回使用逗号作为分隔符的双精度
【发布时间】:2015-06-20 21:57:10
【问题描述】:

我正在制作一个随机文件生成器,它会生成一个带有随机笛卡尔点的 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(",", ".") 解决了这个问题,但我觉得这不是一个好的解决方案,我想知道是否有任何理由在格式方法中使用逗号。

【问题讨论】:

  • 你用的是什么本地的?
  • Locale.getDefault() 在您的系统上返回什么?
  • @MadProgrammer The Anglesey Arms - 为什么这很重要?
  • 您可以使用NumberFormat.getNumberInstance(Locale) 更改值的格式...
  • 签出这个...本地依赖stackoverflow.com/a/7070368/2624806

标签: java string


【解决方案1】:

您应该以适当的方式解决它,而不是使用解决方法(用点替换逗号)。 “有一个 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 (see the Javadoc)。标准是use the default locale,如果需要you are able to change the behavior

【讨论】:

    【解决方案2】:

    试试这个:

            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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-24
      相关资源
      最近更新 更多