"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Safely Parse Doubles with Comma as Decimal Separator in Java?

How to Safely Parse Doubles with Comma as Decimal Separator in Java?

Published on 2024-12-22
Browse:549

How to Safely Parse Doubles with Comma as Decimal Separator in Java?

How to Effectively Parse Double with Comma as Decimal Separator

Problem:

String values representing decimal numbers with commas as separators, like "1,234", can cause NumberFormatException when parsed using Double.valueOf().

Proposed Solution:

Replacing commas with periods using p = p.replaceAll(",", ".") is a valid approach, but there's a more robust method.

Java's NumberFormat for Decimal Parsing:

To handle decimals with locale-specific separators, Java provides NumberFormat. Consider the following code:

NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
Number number = format.parse("1,234");
double d = number.doubleValue();

Update for Multi-Language Applications:

In multilingual applications, locale-specific decimal separators are important. To support this, use NumberFormat.getInstance(Locale.getDefault()) to get the current locale's format.

Advantages of NumberFormat:

  • Handles commas and locale-specific separators.
  • Provides flexibility for various input formats.
  • Ensures parsing and representation are consistent with the set locale.
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3