Java – Android: how do I get two digits after a decimal value? Do not want to truncate the value

How to get a double precision value with only two digits after the decimal point

For example, if a = 190253 80846153846@H_502_10 @Then the result value should be a = 190253.80

Try: @ h_ 502_ 10 @ I tried this:

public static DecimalFormat twoDForm = new DecimalFormat("#0.00");

In code

a = Double.parseDouble(twoDForm.format(((a))));

But the value I get is like 190253.81, not what I want 190253.80

So what should I change for it?

Solution

Because of math Round() returns the int closest to the parameter. Round the result to an integer by adding 1 / 2, take the lowest value of the result, and convert the result to type int@ H_ 502_ 10 @ use math floor()

example

public static double roundMyData(double Rval,int numberOfDigitsAfterDecimal) {
                  double p = (float)Math.pow(10,numberOfDigitsAfterDecimal);
              Rval = Rval * p;
              double tmp = Math.floor(Rval);
              System.out.println("~~~~~~tmp~~~~~"+tmp);
              return (double)tmp/p;
              }

Complete source code

class ZiggyTest2{


        public static void main(String[] args) {  
             double num = 190253.80846153846;
              double round = roundMyData(num,2);
              System.out.println("Rounded data: " + round);
              }

              public static double roundMyData(double Rval,numberOfDigitsAfterDecimal);
              Rval = Rval * p;
              double tmp = Math.floor(Rval);
              System.out.println("~~~~~~tmp~~~~~"+tmp);
              return (double)tmp/p;
              }
            }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>