[英]How to set particular number of Digits in double primitive type in java?
我想要双原始类型的特定位数(小数点前+小数点后)。
有没有办法做到这一点...
例如:(固定为 6 位数字)
为了更清楚地理解,我附上了一张图片。 在此处输入图像描述
有两件事要考虑。 一个是如果您需要精确的精度,因为浮点运算可能无法满足您的要求。 有关详细信息,请参阅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.