我想要一个方法,转换双精度到一个字符串轮,即,如果小数被舍入是5,它总是舍入到以前的数字。这是舍入的标准方法。
我也希望只显示有效数字-也就是说,后面不应该有任何零。
我知道一种方法是使用 String.format :
String.format("%.5g%n", 0.912385);
returns:
0.91239
这个也还行,但它总是显示的数字小数点后5位,把零也显示出来了:
String.format("%.5g%n", 0.912300);
returns:
0.91230
另一个方法是使用DecimalFormatter :
DecimalFormat df = new DecimalFormat("#.#####");
df.format(0.912385);
returns:
0.91238
然而,这接近于四舍五入。也就是说,如果前面的数字是偶数,那么它就会四舍五入。但我想要的是:
0.912385 -> 0.912390.912300 -> 0.9123
在 Java 中实现这一点的最佳方法是什么?
使用 setRoundingMode,设置 RoundingMode 来处理问题,然后使用格式模式输出所需的输出。
例:
DecimalFormat df = new DecimalFormat("#.####");
df.setRoundingMode(RoundingMode.CEILING);for (Number n : Arrays.asList(12, 123.12345, 0.23, 0.1, 2341234.212431324)) {
Double d = n.doubleValue();
System.out.println(df.format(d));}
输出
12123.12350.230.12341234.2125
假设 value 是 double,可以这样做:
(double)Math.round(value * 100000d) / 100000d
是5位数的精度。 零的数目表示小数的数目。
new BigDecimal(String.valueOf(double)).setScale(yourScale, BigDecimal.ROUND_HALF_UP);
示例:
package trials;import java.math.BigDecimal;
public class Trials {
public static void main(String[] args) {
int yourScale = 10;
System.out.println(BigDecimal.valueOf(0.42344534534553453453-0.42324534524553453453).setScale(yourScale, BigDecimal.ROUND_HALF_UP));
}
可以用
DecimalFormat df = new DecimalFormat("#.00000");
df.format(0.912385);