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?
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)
edit
Be very careful when using this method (or any rounding of floating points). It fails for something as simple as 265.335. The intermediate result of 265.335 * 100 (precision of 2 digits) is 26533.499999999996. This means it gets rounded down to 265.33. There simply are inherent problems when converting from floating point numbers to real decimal numbers. See EJP's answer here at https://stackoverflow.com/a/12684082/144578 - How to round a number to n decimal places in Java