views:

36

answers:

1

Hi folks,

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.

input:
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 etc.

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.

Any help is appriciated.

+2  A: 

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.

Jon Skeet
The problem is that the user can do the input independent the locale-settings. So deciding the right locale is a problem.
Arnold
@Arnold: Then you've got a problem. If two different users can enter the same information and mean different things, that's something you'll have to think about. When you've decided what to do, the *technical* aspect may well be simple... but it's a cultural issue more than a technical one.
Jon Skeet
+1 for the example with 1,251 which is a real trouble maker. @Arnold - this sort of design is a usability nightmare waiting to happen. There are users that will not think twice about using the format 1,251 and using it many times expecting different result based on what they need at the time, but you can't really read their mind and give them the value they want. You need to force them to choose a format (locale) and stick to it, otherwise: "I wanted decimal number, not whole number, why won't it work!? Sometimes it gets it right, and sometimes it doesn't!"
Andrei Fierbinteanu
You can of course have different locales per logged in user (through preferences), but once that preference is set make them use it. If they decide to change them later, also convert all previously entered values to that value on the UI.
Andrei Fierbinteanu