Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java BigDecimal can have comma instead dot?

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?

like image 508
Jean Tehhe Avatar asked Sep 10 '13 08:09

Jean Tehhe


People also ask

Can BigDecimal have decimal places?

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.

What can I use instead of BigDecimal?

If you need to use division in your arithmetic, you need to use double instead of BigDecimal.

What is default precision of BigDecimal in Java?

By default, BigDecimal numbers have “unlimited” precision. In fact, the maximum unscaled value is equal to 2^Integer.


3 Answers

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.

like image 172
No Idea For Name Avatar answered Oct 11 '22 12:10

No Idea For Name


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(',', '.').

like image 42
Kayz Avatar answered Oct 11 '22 11:10

Kayz


The BigDecimal(String) constructor documentation lists all valid formats and characters. Notice that the , is not included within this list.

like image 23
Kevin Bowersox Avatar answered Oct 11 '22 11:10

Kevin Bowersox