在 Java 中定义双精度数的小数位

defining decimal places of a double number in Java

我有一个愚蠢的问题。

假设我有某个双数:

double doubleValue=4.1;

有没有办法将此值显示为 4.10 不是 字符串而是双精度值?

如果要打印两位小数,请执行以下操作:

double d = 4.10;
 DecimalFormat df = new DecimalFormat("#.00");
 System.out.print(df.format(d));

这将打印 4.10 并且数字是双精度的

这是一个完整的示例,您可以编译它并 运行 打印 4.10:

import java.text.DecimalFormat;

class twoDecimals {
    public static void main(String[] args) {
double d = 4.10;
 DecimalFormat df = new DecimalFormat("#.00");
 System.out.print(df.format(d));
}
}

即使你设置

double d = 4.1;

它将打印 4.10

如果你设置 double d = 4; 它将打印 4.00 这意味着总是打印两个小数点

就这么办,

double doubleValue=4.1;

String.format(Locale.ROOT, "%.2f", doubleValue );

输出:

4.10

使用这种方法你不需要使用 DecimalFormat 这也将减少 不必要的导入

您无法定义数据类型的精度 double。 如果需要定义小数的精度,可以使用 class BigDecimal。 正如 javadoc 解释的那样,BigDecimal 用于 任意精度带符号的十进制数 。 这里是参考

http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html

我不明白你为什么要双数,小数点后有 2 位数字,中间用 0 补缺。你打算在某个地方展示它吗?

答案是,不,你不能。

实际上,如果 double 后面没有任何 0,您可以设置它的精度。

前 -

4.10000 // and you want to set the precision to 2 digits
// it will still give you 4.1 not 4.10

if it is 4.1 // and you want to set precision to 3 digits
// it will still give you 4.1 not 4.100

if it is 4.1234565 // and you want to set precision to 3 digits,
// it will give you 4.123

即使您使用 String.format 对其进行格式化并将其更改回十进制或使用 BigDecimal 的 setScale 方法设置精度, 你不能得到小数点后以 0 结尾的双精度值。

如果你想在某个地方显示某个小数点,你可以通过转换成字符串来实现。

这里有 2 种方法可以做到这一点,(将设置精度但不会在最后设置 0 来填补空白)

1.

int numberOfDigitsAfterDecimal = 2;
double yourDoubleResult = 4.1000000000;
Double resultToBeShown = new BigDecimal(yourDoubleResult).setScale(numberOfDigitsAfterDecimal, BigDecimal.ROUND_HALF_UP).doubleValue();
System.out.println(resultToBeShown);

2.

double doubleValue=4.1;
double newValue = Double.parseDouble(String.format( "%.2f", doubleValue ));
System.out.println(newValue);

为了得到 4.10 作为字符串,

double doubleValue=4.1;
String newValue = String.format( "%.2f", doubleValue );
System.out.println(newValue);