Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double value to round up in Java

I have a double value = 1.068879335 i want to round it up with only two decimal values like 1.07.

I tried like this

DecimalFormat df=new DecimalFormat("0.00"); String formate = df.format(value); double finalValue = Double.parseDouble(formate) ; 

this is giving me this following exception

java.lang.NumberFormatException: For input string: "1,07"      at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1224)      at java.lang.Double.parseDouble(Double.java:510) 

can some one tell me what is wrong with my code.

finaly i need the finalValue = 1.07;

like image 434
jimmy Avatar asked Jan 25 '11 17:01

jimmy


People also ask

How do you round up a double in Java?

1 Answer. double roundOff = (double) Math. round(a * 100) / 100; this will do it for you as well.

How do you round up double value?

Using Math.round() accepts a double value and converts it into the nearest long value by adding 0.5 to the value and truncating its decimal points. The long value can then be converted to an int using typecasting.

Does double to int round up Java?

If you want to convert floating-point double value to the nearest int value then you should use the Math. round() method. It accepts a double value and converts into the nearest long value by adding 0.5 and truncating decimal points.

How do you round up a value in Java?

Java Math round()The round() method rounds the specified value to the closest int or long value and returns it. That is, 3.87 is rounded to 4 and 3.24 is rounded to 3.


1 Answers

Note the comma in your string: "1,07". DecimalFormat uses a locale-specific separator string, while Double.parseDouble() does not. As you happen to live in a country where the decimal separator is ",", you can't parse your number back.

However, you can use the same DecimalFormat to parse it back:

DecimalFormat df=new DecimalFormat("0.00"); String formate = df.format(value);  double finalValue = (Double)df.parse(formate) ; 

But you really should do this instead:

double finalValue = Math.round( value * 100.0 ) / 100.0; 

Note: As has been pointed out, you should only use floating point if you don't need a precise control over accuracy. (Financial calculations being the main example of when not to use them.)

like image 172
biziclop Avatar answered Sep 21 '22 03:09

biziclop