Reputation: 17375
I have a input file coming into my application with some product prices values in each rows.
However, when the price is higher then 999.99, the values contain , at appropriate place.
1,000.00
5,432.89
etc.
1) Is there a set rule about placing comma in currency values ? On what basis the place of comma is decided ?
2) Is there a library method to parse such string values to float/double ?
Thanks for reading!!
Upvotes: 4
Views: 1746
Reputation: 1500495
You can use DecimalFormat
to parse and format decimal numbers.
The commas are there for thousands separators. Here's a simple example which deliberately parses to BigDecimal
rather than to float
or double
- binary floating point is inappropriate 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 just uses the default locale for things like the thousands separator and the decimal separator - you may well want to specify a particular locale, if you know what will be used for the file you need to parse.
Upvotes: 5