folone folone - 6 months ago 27
Java Question

DecimalFormat and Double.valueOf()

I'm trying to get rid of unnecessary symbols after decimal seperator of my double value. I'm doing it this way:

DecimalFormat format = new DecimalFormat("#.#####");
value = Double.valueOf(format.format(41251.50000000012343));


But when I run this code, it throws:

java.lang.NumberFormatException: For input string: "41251,5"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1224)
at java.lang.Double.valueOf(Double.java:447)
at ...


As I see,
Double.valueOf()
works great with strings like
"11.1"
, but it chokes on strings like
"11,1"
. How do I work around this? Is there a more elegant way then something like

Double.valueOf(format.format(41251.50000000012343).replaceAll(",", "."));


Is there a way to override the default decimal separator value of
DecimalFormat
class? Any other thoughts?

Answer

By

get rid of unnecessary symbols after decimal seperator of my double value

do you actually mean you want to round to e.g. the 5th decimal? Then just use

value = Math.round(value*1e5)/1e5;

(of course you can also Math.floor(value*1e5)/1e5 if you really want the other digits cut off)