Reputation: 77
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". 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.
Upvotes: 2
Views: 2495
Reputation: 22971
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."
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). Standard is use the default locale
and if needed you are able to change the behavior
.
Upvotes: 3
Reputation: 1680
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
Upvotes: 2