Pergunta

For example, I have the number 137.99999999999. How do you format that to one decimal place like 137.9?

Another example would be 4.7777777777 to 4.7

Note: I don't want to round the number at all. I just want to truncate it to one decimal place.

Foi útil?

Solução

Use NumberFormat if you need more special approaches as to display 4.77 as 4.7, not as 4.8 (this is RoundingMode.DOWN):

  NumberFormat format = NumberFormat.getInstance();
  format.setRoundingMode(RoundingMode.DOWN);
  format.setMaximumFractionDigits(2);
  System.out.println(format.format(4.7777));

The output is 4.77

Outras dicas

You can find an elaborate answer here : Round a double to 2 decimal places

Tweak it for 1 decimal place and you're good to go.

Or, another simple way to truncate to one decimal point would be :

String numberString = "137.99999999999";
int indexOfDecimal = numberString.indexOf('.');
Double truncatedNumber = new Double(numberString.subString(0,indexOfDecimal+2));
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top