With the following code I only want to allow positive numbers. For some reason i am not even able to parse the strings correctly:
DecimalFormat dfNoNegative = new DecimalFormat("#,##0.00");
dfNoNegative.setNegativePrefix("");
try {
System.out.println(dfNoNegative.parse("123.00"));
} catch (ParseException e) {
System.out.println(e.getMessage());
System.out.println(e.getErrorOffset());
e.printStackTrace();
}
Error message and ErrorOffset:
Unparseable number: "123.00"
6
Can anyone guide me where I am mistaken? An example for a working String would be good as well
My mistake was to dfNoNegative.setNegativePrefix("");
to nothing (""
). This doesn't work, because the String started directly with the number and 123
is not ""
, and therefore it fails. Basically this method overwrites what should be used as negative prefix (default is -
). If you set it to !
as example, System.out.println(dfNoNegative.parse("!123.00"));
would print -123
.