[英]How to format a decimal number to 2 or 3 digits?
I'm writing a convertor by Eclipse and my results are with 9 or 10 decimal digits and I want to make it 2 or 3. This is part of my code: 我正在用Eclipse写一个转换器,我的结果是9或10个十进制数字,我想将其设置为2或3。这是我的代码的一部分:
double gr = 0;
if (edtGr.getText().toString().length() > 0) {
gr = Float.parseFloat(edtGr.getText().toString());
}
if (edtNgr.getText().toString().length() > 0) {
gr = (Double.parseDouble(edtNgr.getText().toString())) / 1000000000;
}
edtNgr.setText("" + (gr * 1000000000));
edtGr.setText("" + gr);
This code converts grams to nanograms and I want the result in 2 or 3 decimal digits. 这段代码将克转换为毫微克,我想要2或3个十进制数字的结果。
Try 尝试
String.format("%.2f", gr * 1000000000);
For 3 decimal places, 对于小数点后三位,
String.format("%.3f", gr * 1000000000);
For 2 Decimal places change your code as 对于2个小数位,将您的代码更改为
edtNgr.setText(""+ ((String.format("%.2f", (gr * 1000000000)))));
edtGr.setText("" + ((String.format("%.2f", gr))));
And for 3 Decimal points 还有3个小数点
edtNgr.setText("" + ((String.format("%.3f", (gr * 1000000000)))));
edtGr.setText("" + ((String.format("%.3f", gr))));
Also You can use DecimalFormat
. 您也可以使用
DecimalFormat
。 One way for (using 3 points) to use it: 一种(使用3分)使用它的方法:
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(3);
edtNgr.setText("" + df.format(gr * 1000000000));
edtGr.setText("" +df.format(gr));
Please see more at How to format Decimal Number in Java 请参见如何在Java中格式化小数
You can use 您可以使用
double roundOff = Math.round(yourDouble * 1000.0) / 1000.0;
Another way 其他方式
BigDecimal doubleVal = new BigDecimal("123.13698");
BigDecimal roundOff = doubleVal.setScale(2, BigDecimal.ROUND_HALF_EVEN);
You can use NumberFormatter
like 您可以像这样使用
NumberFormatter
NumberFormat formatter = NumberFormat.getInstance();
formatter.setMaximumFractionDigits(3);
then format it like 然后像这样格式化
formatter.format(36.55468865)
This will give the output 36.555
rounding off 55468865
to 555
这会给输出
36.555
四舍五入55468865
至555
(double)Math.round(value * 100000) / 100000.. the number of precision indicated by the number of zeros. (double)Math.round(value * 100000)/ 100000 ..精度数由零个数表示。
Or 要么
double d = 12345.2145; 双倍d = 12345.2145;
BigDecimal bd = new BigDecimal(d).setScale(3, RoundingMode.HALF_EVEN); BigDecimal bd = new BigDecimal(d).setScale(3,RoundingMode.HALF_EVEN); d = bd.doubleValue();
d = bd.doubleValue();
Change the 1st argument in setScale method as per the precision required. 根据所需的精度更改setScale方法中的第一个参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.