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;
You can use format like here,
The problem is that you use a localizing formatter that generates locale-specific decimal point, which is "," in your case. But Double.parseDouble() expects non-localized double literal. You could solve your problem by using a locale-specific parsing method or by changing locale of your formatter to something that uses "." as the decimal point. Or even better, avoid unnecessary formatting by using something like this:
Live @Sergey's solution but with integer division.
prints
EDIT: As Sergey points out, there should be no difference between multipling double*int and double*double and dividing double/int and double/double. I can't find an example where the result is different. However on x86/x64 and other systems there is a specific machine code instruction for mixed double,int values which I believe the JVM uses.
Prints
This is not possible in the requested way because there are numbers with two decimal places which can not be expressed exactly using IEEE floating point numbers (for example 1/10 = 0.1 can not be expressed as a
Double
orFloat
). The formatting should always happen as the last step before presenting the result to the user.I guess you are asking because you want to deal with monetary values. There is no way to do this reliably with floating-point numbers, you shoud consider switching to fixed-point arithmetics. This probably means doing all calculations in "cents" instead of "dollars".
You could try defining a new DecimalFormat and using it as a Double result to a new double variable.
Example given to make you understand what I just said.
Try this: org.apache.commons.math3.util.Precision.round(double x, int scale)
See: http://commons.apache.org/proper/commons-math/apidocs/org/apache/commons/math3/util/Precision.html
Apache Commons Mathematics Library homepage is: http://commons.apache.org/proper/commons-math/index.html
The internal implemetation of this method is: