Enrico Susatyo Enrico Susatyo - 1 year ago 131
Groovy Question

Formatting currency in String from different locale currency formats

I have a java string variable in my groovy app. The variable contains a user input of price in possibly different currency formats:

val = "1,250.50"
val = "1.250,50"
val = "1250,50"
val = "1250.50"

(etc.. I don't know if there are anymore funny way other countries write this)

Is there a way to parse this to the appropriate double value regardless of the format? Looking at this at the moment but not sure if it'll help. My current method only works for the US format:

total = Double.parseDouble(val.replace('$','').replaceAll(",","").trim())

Answer Source

You cannot parse it without knowing what the user will use as decimal separator, grouping separator, ... . For example if I type 1,250 you do not know whether I mean one thousand two hundred fifty (1,250.00), or one point two hundred fifty (1.250) . That's why the NumberFormat/DecimalFormat class of Java allows you to specify the grouping and decimal separator.

What you could do is hoping that the user inputs his values using the conventions corresponding to his Locale settings, and use the

NumberFormat.getInstance( Locale )

with the current Locale of the JVM.

Note: with the NumberFormat you can also parse a currency. See NumberFormat#getCurrencyInstance

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download