I have this code:
public String formatDouble(double d) { return String.format("???", d); //Should I use NumberFormat here? }
To enter a sample:
1.00 1,00 1,23 1.234567
I would like to get this output:
1 1 1.23 1.234
How to set up a template (or possibly an instance of NumberFormat) to create the correct output?
This will do roughly what you need:
Decimalformat df = new DecimalFormat("0.###"); df.setRoundingMode(RoundingMode.FLOOR); df.format(1.2345);
However, the decimal separator (period) will depend on the current locale. To cancel it, you can specify your own format characters (see DecimalFormat.setDecimalFormatSymbols()).
DecimalFormat.setDecimalFormatSymbols()
DecimalFormat should do what you need.
: String.format("%.2f", 1234.23)
String.format("%.2f", 1234.23)
If you need a thousands separator, add a comma to the point: String.format("%,.2f", 1234.23)→ Result: 1,234.23.
String.format("%,.2f", 1234.23)
1,234.23