Reputation: 3
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:
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.
Upvotes: 0
Views: 4786
Reputation: 14398
For 2 Decimal places change your code as
edtNgr.setText(""+ ((String.format("%.2f", (gr * 1000000000)))));
edtGr.setText("" + ((String.format("%.2f", gr))));
And for 3 Decimal points
edtNgr.setText("" + ((String.format("%.3f", (gr * 1000000000)))));
edtGr.setText("" + ((String.format("%.3f", gr))));
Also You can use DecimalFormat
. One way for (using 3 points) to use it:
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
Upvotes: 1
Reputation: 971
(double)Math.round(value * 100000) / 100000.. the number of precision indicated by the number of zeros.
Or
double d = 12345.2145;
BigDecimal bd = new BigDecimal(d).setScale(3, RoundingMode.HALF_EVEN); d = bd.doubleValue();
Change the 1st argument in setScale method as per the precision required.
Upvotes: 0
Reputation: 13520
You can use NumberFormatter
like
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
Upvotes: 0
Reputation: 2897
Try
String.format("%.2f", gr * 1000000000);
For 3 decimal places,
String.format("%.3f", gr * 1000000000);
Upvotes: 2
Reputation: 10083
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);
Upvotes: 0