How to parseDouble with comma as decimal separator in java?

How to parseDouble with comma as decimal separator in java?

To parse a double with a comma as the decimal separator in Java, you can use the DecimalFormat class from the java.text package. Here's an example of how to do this:

import java.text.DecimalFormat; import java.text.ParseException; public class ParseDoubleWithComma { public static void main(String[] args) { String numberString = "123,456.78"; // Example string with comma as decimal separator DecimalFormat decimalFormat = new DecimalFormat("#,##0.##"); try { double parsedValue = decimalFormat.parse(numberString).doubleValue(); System.out.println("Parsed Double: " + parsedValue); } catch (ParseException e) { e.printStackTrace(); } } } 

In this example:

  1. We have a string numberString containing a number with a comma as the decimal separator (e.g., "123,456.78").

  2. We create a DecimalFormat instance called decimalFormat with a pattern that matches the expected format of the number. The pattern #,##0.## specifies that thousands should be separated by commas and that the number can have up to two decimal places.

  3. We use decimalFormat.parse(numberString) to parse the string into a java.text.Number object. The doubleValue() method is then used to extract the double value.

  4. Finally, we print the parsed double value to the console.

This code will correctly parse a double value with a comma as the decimal separator. Make sure to handle exceptions appropriately when parsing to account for potential parsing errors, such as invalid input strings.


More Tags

environment aws-sdk-ruby home-directory pycrypto advanced-custom-fields non-printing-characters pyscripter git-filter-branch angular-ngmodel rx-java

More Java Questions

More Everyday Utility Calculators

More Electrochemistry Calculators

More Stoichiometry Calculators

More Bio laboratory Calculators