Java 十进制格式舍入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6447153/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 06:01:19  来源:igfitidea点击:

DecimalFormat rounding

javafloating-pointdecimal

提问by mainstringargs

Here is small code to illustrate what I am seeing

这是小代码来说明我所看到的

float floater = 59.999f;

DecimalFormat df = new DecimalFormat("00.0");

System.out.println(df.format(floater));

This prints:

这打印:

60.0

I would like it to print

我想打印

59.9

What do I need to do?

我需要做什么?

采纳答案by Michael Borgwardt

Add this line before using the DecimalFormat:

在使用之前添加这一行DecimalFormat

df.setRoundingMode(RoundingMode.DOWN);

Take a look at the other rounding modes and see which one is best for you.

看看其他舍入模式,看看哪一种最适合您。

Note : this method works only in JDK 1.6 or above

注意:此方法仅适用于 JDK 1.6 或更高版本

回答by Pablo Fernandez

float d = 59.999f;
BigDecimal bd = new BigDecimal(d);
// Use the returned value from setScale, as it doesn't modify the caller.
bd = bd.setScale(1, BigDecimal.ROUND_FLOOR);
String formatted = bd.toString();