문제

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.

도움이 되었습니까?

해결책

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

다른 팁

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));
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top