Sometimes it is not clear which decimal seperator is used. You can have a dot or a comma without knowing for sure. This input might come up:
- 1.52
- 1,52
- 1.500,61
- 1,500.61
- 1,500,200.23
- 1.500.200,23
Using this technique helps converting in a lot of cases:
public static double convert(String input) {
input = input.replace(',', '.');
int decimalSeperator = input.lastIndexOf('.');
if (decimalSeperator > -1) {
input = input.substring(0, decimalSeperator).replace(".", "") + input.substring(decimalSeperator);
}
return Double.valueOf(input);
}
@Test
public void convertTest() {
assertEquals(0.2, Util.convert(".2"), 0.000001);
assertEquals(0.2, Util.convert(",2"), 0.000001);
assertEquals(1, Util.convert("1,"), 0.000001);
assertEquals(2, Util.convert("2."), 0.000001);
assertEquals(1, Util.convert("1"), 0.000001);
assertEquals(1.52, Util.convert("1.52"), 0.000001);
assertEquals(1.52, Util.convert("1,52"), 0.000001);
assertEquals(1.5, Util.convert("1.500"), 0.000001);
assertEquals(1.5, Util.convert("1,500"), 0.000001);
assertEquals(1500.61, Util.convert("1.500,61"), 0.000001);
assertEquals(1500.61, Util.convert("1,500.61"), 0.000001);
assertEquals(1500.2, Util.convert("1,500,200"), 0.000001);
assertEquals(1500.2, Util.convert("1.500.200"), 0.000001);
assertEquals(1500200.23, Util.convert("1500200.23"), 0.000001);
assertEquals(1500200.23, Util.convert("1500200,23"), 0.000001);
assertEquals(1500200.23, Util.convert("1,500,200.23"), 0.000001);
assertEquals(1500200.23, Util.convert("1.500.200,23"), 0.000001);
}
But keep in mind that there are also some ambiguous cases which cannot be converted without further information. For example, think about 1.500 – is it 1500 or 1,5?