Android Number Format

In my application, I need to round to two significant digits after the decimal point. I tried the code below.

public static double round(double value, int places) { long factor = (long) Math.pow(10, places); value = value * factor; long tmp = Math.round(value); return (double) tmp / factor; } 

also i tried

 double val = ....; val = val*100; val = (double)((int) val); val = val /100; 

Both codes do not work for me.

Thanks in advance....

+6
source share
6 answers

As Grammin said, if you are trying to introduce money, use BigDecimal . This class supports all kinds of rounding, and you can precisely set the desired accuracy.

But for a direct answer to your question, you cannot set the precision to double, because it is a floating point. He does not have accuracy. If you just need to do this to format the output, I would recommend using NumberFormat . Something like that:

 NumberFormat nf = NumberFormat.getInstance(); nf.setMinimumFractionDigits(2); nf.setMaximumFractionDigits(2); String output = nf.format(val); 
+19
source

Or you can use java.text.DecimalFormat :

 String string = new DecimalFormat("####0.00").format(val); 
+6
source

I would recommend using BigDecimal if you are trying to imagine a currency.

This example may be helpful.

+2
source

As Gramming said, you could use BigDecimals for this or NumberFormat to make sure the number of digits displayed

0
source

Your code works with me

 double rounded = round(0.123456789, 3); System.out.println(rounded); >0.123 

Edit: just looked at your new comment on your question. This is a formatting issue, not a math issue.

0
source

I decided to use everything as an int. There are no problems on this way.

 DecimalFormatSymbols currencySymbol = DecimalFormatSymbols.getInstance(); NumberFormat numberF = NumberFormat.getInstance(); 

after...

 numberF.setMaximumFractionDigits(2); numberF.setMinimumFractionDigits(2); TextView tv_total = findViewById(R.id.total); int total = doYourStuff();//calculate the prices tv_total.setText(numberF.format(((double)total)/100) + currencySymbol.getCurrencySymbol()); 
0
source

Source: https://habr.com/ru/post/887929/


All Articles