简体   繁体   中英

How do you shorten a long decimal number in Java?

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM