Home > Blockchain >  Trim from String after decimal places to 18 places in java - roundoff not required)
Trim from String after decimal places to 18 places in java - roundoff not required)

Time:03-08

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 ?

CodePudding user response:

Put it in a method, and test several alternatives to see which is better. You will have to first define what "better" means for your specific use-case: less memory? faster?

I propose:

public static String trimDecimalPlaces(String input, int places) {
    int dotPosition = input.indexOf(".");
    int targetSize = dotPosition   places   1;
    if (dotPosition == -1 || targetSize > input.length()) {
        return input;
    } else {
        return input.substring(0, targetSize);
    }
}

This has a speed advantage over regex-based solutions, but it is certainly longer in terms of code.

CodePudding user response:

Use regex for a one line solution:

str = str.replaceAll("(?<=\\..{18}).*", "");

See live demo.

CodePudding user response:

You could use a regex replacement here:

String str = "0.0040000000000000001";
String output = str.replaceAll("(\\d \\.\\d{18})(\\d )", "$1");
System.out.println(output); // 0.004000000000000000
  • Related