Parsing string value from file to float, where the string contains a comma

I have an input file included in my application with some price values ​​for goods on each line.

However, when the price is above 999.99, the values ​​are kept in the appropriate place.

1,000.00 5,432.89 

etc..

1) Is there an established rule on placing a comma in currency values? On what basis is a comma determined?

2) Is there a library method for parsing such string values ​​for float / double?

Thank you for reading!

+4
source share
1 answer

You can use DecimalFormat to parse and format decimal numbers.

There are separators for thousands of separators. Here's a simple example that deliberately parses on a BigDecimal , and not on a float or double - a binary floating point, not suitable for currency values.

 import java.math.*; import java.text.*; public class Test { public static void main(String[] args) throws Exception { DecimalFormat format = new DecimalFormat(); format.setParseBigDecimal(true); BigDecimal value = (BigDecimal) format.parse("1,234.56"); System.out.println(value); } } 

Now that you are only using the default locale for things like the thousands separator and decimal separator, you might want to specify a specific locale if you know what will be used for the file you need to parse.

+5
source

Source: https://habr.com/ru/post/1383800/


All Articles