I want to be able to convert a string to a Double given a number of decimal places in a format string. So \"###,##0.000\" should give me a Double>
The restriction of decimal places in DecimalFormat is really meant for use in the format() method and doesn't have much effect in the parse() method.
In order to get what you want you need this:
try {
// output current locale we are running under (this happens to be "nl_BE")
System.out.println("Current Locale is " + Locale.getDefault().toString());
// number in Central European Format with a format string specified in UK format
String numberCE = "1,234567"; // 1.234567
String formatUK = "###,##0.000";
// do the format
DecimalFormat formatterUK = new DecimalFormat(formatUK);
Double valCEWithUKFormat = formatterUK.parse(numberCE).doubleValue();
// first convert to UK format string
String numberUK = formatterUK.format(valCEWithUKFormat);
// now parse that string to a double
valCEWithUKFormat = formatterUK.parse(numberUK).doubleValue();
// I want the number to DPs in the format string!!!
System.out.println("CE Value " + numberCE + " in UK format (" + formatUK + ") is " + valCEWithUKFormat);
} catch (ParseException ex) {
System.out.println("Cannot parse number");
}
You first need to get the number as a UK format string and then parse that number, using the UK formatter. That will get you the result you're looking for. NB, this will round the number to 3 decimal places, not truncate.
By the way, I'm slightly surprised that your UK formatter is able to parse the CE format number. You really should be parsing the original number with a CE format parser.