I have some code that checks how many decimals my number has.
Example:
1,10 correct conversion:
String.format("%.1f", Double.parseDouble(md.get("amount"))
1,10 incorrect conversion:
String.format("%.2f", Double.parseDouble(md.get("amount"))
I cannot have trailing 0's
1 correct conversion:
String.format("%.0f", Double.parseDouble(md.get("amount"))
1 incorrect conversion:
String.format("%.1f", Double.parseDouble(md.get("amount"))
I cannot have trailing 0's
For numbers larger than 1 000 000 Java converts my numbers to scientific notation, and the only way i know to convert them back without losing decimals is to use String.format.
My bad code:
md is a map, and the key "amount" maps to a String that is supposed to be a Double
if( Double.parseDouble(md.get("amount")) * 10 % 10 != 0) {
System.out.println("0,1");
md.put("amount", String.format("%.1f", Double.parseDouble(md.get("amount"))));
if( Double.parseDouble(md.get("amount")) * 100 % 10 != 0) {
System.out.println("0,11");
md.put("amount", String.format("%.2f", Double.parseDouble(md.get("amount"))));
}
}
else if(Double.parseDouble(md.get("amount")) * 10 % 10 == 0 && Double.parseDouble(md.get("amount")) * 100 % 10 == 0){
System.out.println("0,0");
md.put("amount", String.format("%.0f", Double.parseDouble(md.get("amount"))));
}