Search code examples
javalocaledecimalformat

String getting parsed incorrectly by DecimalFormat with different locales


Code:-

((DecimalFormat)DecimalFormat.getInstance(new Locale("en","US"))).parse("0.5")

output: 0.5

Code :-

((DecimalFormat)DecimalFormat.getInstance(new Locale("es","CN"))).parse("0.5")

output : 5

I am using the DecimalFormat to format the string into number, but it is somehow not giving the expected results for different locales. Please help me with getting same output for all locales.


Solution

  • You are inputting "es" in Locale, so you are parsing it as a Spanish way to parse the String. In Spanish, the decimal separator is a comma. So 0.5 becomes 5.