[英]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 位数字)
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.