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
do you actually mean you want to round to e.g. the 5th decimal? Then just use
(of course you can also
Math.floor(value*1e5)/1e5
if you really want the other digits cut off)The problem is that your decimal format converts your value to a localized string. I'm guessing that your default decimal separator for your locale is with a '
,
'. This often happens with French locales or other parts of the world.Basically what you need to do is create your formatted date with the '.' separator so
Double.valueOf
can read it. As indicated by the comments, you can use the same format to parse the value as well instead of usingDouble.valueOf
.You can't change the internal representation of
double
/Double
that way.If you want to change the (human) representation, just keep it
String
. Thus, leave thatDouble#valueOf()
away and use theString
outcome ofDecimalFormat#format()
in your presentation. If you ever want to do calculations with it, you can always convert back to a realDouble
usingDecimalFormat
andDouble#valueOf()
.By the way, as per your complain I'm trying to get rid of unnecessary symbols after decimal seperator of my double value, are you aware of the internals of floating point numbers? It smells a bit like that you're using unformatted doubles in the presentation layer and that you didn't realize that with the average UI you can just present them using
DecimalFormat
without the need to convert back toDouble
.For the '
,
' instead of the '.
' , you'd have to change the locale.For the number of decimals, use
setMaximumFractionDigits(int newValue)
.For the rest, see the javadoc.