简体   繁体   English

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

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

I want a particular number of digits (before decimal + after decimal) in double primitive type.我想要双原始类型的特定位数(小数点前+小数点后)。

Is there any way to do this...有没有办法做到这一点...

For eg: (fixed to 6 digits)例如:(固定为 6 位数字)

  1. If we have 12.666666667 gives output as 12.6667如果我们有 12.666666667 给出 output 为 12.6667
  2. If we have 5.6666666667 gives output as 5.66667如果我们有 5.6666666667 给出 output 为 5.66667
  3. But , If we have 9.00000000 gives output as only 9.但是,如果我们有 9.00000000,则 output 只有 9。

For, more clear understanding, I have attached an image.为了更清楚地理解,我附上了一张图片。 enter image description here在此处输入图像描述

Two things to consider.有两件事要考虑。 One is if you need an exact precision, since floating point arithmetic might not give you that.一个是如果您需要精确的精度,因为浮点运算可能无法满足您的要求。 See the BigDecimal class for more information.有关详细信息,请参阅BigDecimal class。 The other is what you're trying to do: display a number with a certain number of decimal places.另一个是你想要做的:显示一个带有一定小数位数的数字。 You can accomplish this with String.format .您可以使用String.format完成此操作。 For example例如

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

And

System.out.println(formatted)

Will output将 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