繁体   English   中英

如何在 java 中设置双原始类型的特定位数?

[英]How to set particular number of Digits in double primitive type in java?

我想要双原始类型的特定位数(小数点前+小数点后)。

有没有办法做到这一点...

例如:(固定为 6 位数字)

  1. 如果我们有 12.666666667 给出 output 为 12.6667
  2. 如果我们有 5.6666666667 给出 output 为 5.66667
  3. 但是,如果我们有 9.00000000,则 output 只有 9。

为了更清楚地理解,我附上了一张图片。 在此处输入图像描述

有两件事要考虑。 一个是如果您需要精确的精度,因为浮点运算可能无法满足您的要求。 有关详细信息,请参阅BigDecimal class。 另一个是你想要做的:显示一个带有一定小数位数的数字。 您可以使用String.format完成此操作。 例如

double num = 5.666666666;
String formatted = String.format("%.5f", num);

System.out.println(formatted)

将 output

5.66667
import java.text.DecimalFormat;

public class rounding {
    public static void main(String[] args) {
        double num = 23.122345899;
        double rounded = Math.round(num * 1000000) / 1000000.0;
        System.out.println(rounded);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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