I have a string value that I want to assign to a BigDecimal. When I update the decimal value with a number like 100.23
, it works fine but when I update it with a number like 100,23
the code throws an exception. Why is that?
Immutable, arbitrary-precision signed decimal numbers. A BigDecimal consists of an arbitrary precision integer unscaled value and a 32-bit integer scale. If zero or positive, the scale is the number of digits to the right of the decimal point.
If you need to use division in your arithmetic, you need to use double instead of BigDecimal.
By default, BigDecimal numbers have “unlimited” precision. In fact, the maximum unscaled value is equal to 2^Integer.
because you tried to put a "," in a number.
you can use this code to parse a number with comma:
NumberFormat.getNumberInstance(Locale.FRANCE).parse("265,858")
you should also use float or double if there is no particular reason you use decimal.
If you can't be sure if your String has commas or points, you can use replace(char, char)
from the String class. For example myString.replace(',', '.')
.
The BigDecimal(String)
constructor documentation lists all valid formats and characters. Notice that the ,
is not included within this list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With