问题
I have this code:
public String formatDouble(double d) {
return String.format("???", d); //Should I use NumberFormat here?
}
For the sample input:
1.00
1,00
1,23
1.234567
I would like to get this output:
1
1
1.23
1.234
How can I configure the pattern (or maybe NumberFormat instance) for producing the correct output?
回答1:
This would do roughly what you need:
Decimalformat df = new DecimalFormat("0.###");
df.setRoundingMode(RoundingMode.FLOOR);
df.format(1.2345);
However, the decimal separator (the dot) will be dependent on current locale. To override it, you may want to provide your own format symbols (see DecimalFormat.setDecimalFormatSymbols()
).
回答2:
DecimalFormat should do what you need.
回答3:
Simple way: String.format("%.2f", 1234.23)
If you need thousand separator, add a comma before the dot: String.format("%,.2f", 1234.23)
-> the result: 1,234.23
.
来源:https://stackoverflow.com/questions/8712504/how-to-make-strings-from-floating-point-numbers-with-dot-as-a-decimal-sepa