Arnold
Arnold

Reputation: 1

Conversion of a string to a bigDecimal

My problem is that I have a user input field, which is a textfield, and I have to convert it to a bigDecimal for use at the database.

2,50      --> 2,50  
2.50      --> 2,50  
2.5       --> 2,50  
1200      --> 1200 (or 1200,00)  
1.200     --> 1200 (or 1200,00)  
1.200,50  --> 1200,50  
1,200.50  --> 1200,50

Is there a simple way to convert all these kind of inputs? The use of valueOf or parseDouble does not do the job. I also tried the DecimalFormatter, but I can't find the correct format.

Upvotes: 0

Views: 1783

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503779

DecimalFormat is the way to go - get the appropriate DecimalFormat for the user's locale, and call setParseBigDecimal(true) so that it parses to BigDecimal rather than double.

Note that you really need to know the right locale - otherwise "1,251" could mean "a bit more than one and a quarter" or "the integer 1251". Admittedly you could try to parse it with every format available and guess which is the right one out of formats that succeed, but that doesn't sound like a great idea to me.

Upvotes: 2

Related Questions