Double value to round up in Java -
i have double value = 1.068879335 want round 2 decimal values 1.07.
i tried this
decimalformat df=new decimalformat("0.00"); string formate = df.format(value); double finalvalue = double.parsedouble(formate) ; this giving me following exception
java.lang.numberformatexception: input string: "1,07" @ sun.misc.floatingdecimal.readjavaformatstring(floatingdecimal.java:1224) @ java.lang.double.parsedouble(double.java:510) can 1 tell me wrong code.
finaly need finalvalue = 1.07;
note comma in string: "1,07". decimalformat uses locale-specific separator string, while double.parsedouble() not. happen live in country decimal separator ",", can't parse number back.
however, can use same decimalformat parse back:
decimalformat df=new decimalformat("0.00"); string formate = df.format(value); double finalvalue = (double)df.parse(formate) ; but should instead:
double finalvalue = math.round( value * 100.0 ) / 100.0; note: has been pointed out, should use floating point if don't need precise control on accuracy. (financial calculations being main example of when not use them.)
Comments
Post a Comment