I am working on a legacy code where i have String field which hold some amount value, which should have only 18 char after decimal place, not more than that.
I have achieved this like below –
String str = "0.0040000000000000001"; String[] values = StringUtils.split(str,"."); System.out.println(str); String output = values[1]; if(output.length()>18){ output = output.substring(0,18); } System.out.println(values[0]+"."+output); // 0.004000000000000000
Is there any better way to do this ?
Advertisement
Answer
Use regex for a one line solution:
str = str.replaceAll("(?<=\..{18}).*", "");
See live demo.