How to make strings from floating point numbers using. (dot) as a decimal separator and not more than 3 digits after a floating point?

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?

+1
source share
3 answers

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

+2
source

DecimalFormat should do what you need.

0

: 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.

0
source

All Articles