简体   繁体   中英

Remove leading zero and delimiter char for BigDecimal

Our application can get following numbers:

0.1
0.02
0.003

etc.

These values treated by our code as BigDecimal ,as far we operate with money.

There is form on web UI, where user should view these floating parts of prices, transformed to following ones:

1
02
003

The question is,how to trim leading zero and delimiter character in input prices. Perhaps BigDecimal class has standard method something like trimLeadingZeroes(),but can't find any.

UPDATE: trim just leading zero and delimiter symbol

For instance:

1 is 0.1

27 is 0.27

Something like this?

public String getDecimalFractions(BigDecimal value) {
    String strValue = value.toPlainString();
    int index = strValue.indexOf(".");
    if(index != -1) {
        return strValue.substring(index+1, strValue.length());
    } 
    return "0"; 
}

Have you tried calling BigDecimal.unscaledValue ? The downside is that 0.13 would then be 13 whereas you possibly want 1.3... it's slightly hard to tell. If you could give more examples, that would really help.

(That approach would also fail if the value were 1000 to start with - you'd end up with 1...)

Could it be something as simple as doing this:

public static BigDecimal fix(String str){
    return  new BigDecimal("0." + str);
}

so if you make

public static void main(String[] args) {
    System.out.println(fix("1"));
    System.out.println(fix("02"));
    System.out.println(fix("003"));
}

It will print

0.1
0.02
0.003

when ever you have to deal with splitting something its a good bet Strings can be used for it.

You first just convert the bigdecimal into a string

String s=bd.toPlainString();

Then you simply split it as so

String s2=s.split("\\.")[1];

now String s2 contains the numbers after the delimiter

Conversion from BigDecimal to String :

    import java.math.BigDecimal;
    public class XXX {
        public static void main(String[] args){
            doIt("123");
            doIt("123.1");
            doIt("123.01");
            doIt("123.0123");
            doIt("123.00123");
        }
        static void doIt(String input){
            BigDecimal bdIn = new BigDecimal(input);
            System.out.println(bdIn+" -> "+convert(bdIn));
        }
        static String convert(BigDecimal bdIn) {
            BigDecimal bdOut = bdIn.subtract(bdIn.setScale(0, BigDecimal.ROUND_DOWN));
            return bdOut.signum() == 0 ? "0" : bdOut.toPlainString().substring(2);
        }
    }

Results are:

    123 -> 0
    123.1 -> 1
    123.01 -> 01
    123.0123 -> 0123
    123.00123 -> 00123

The code works directly with any number and takes into account only the fractional part. It also handles "0.0" gracefully.

Is this the conversion you wanted?

Here is another simple way of doing this - assuming your input is 1.023456

        BigDecimal bd = new BigDecimal("1.023456");
        BigInteger bi = bd.toBigInteger();
        BigDecimal bd2 = bd.subtract(new BigDecimal(bi));
        String afterDecimalPoint = bd2.scale() > 0 ?
               bd2.toString().substring(2) : "";

This will give the exact result as you were looking for in bd3, ie it'll be 023456 for the above example.

It'll work ok for whole numbers too, due to the condition in last line, ie 1 will return ""

您可以使用valueBigDecimal )和StringUtils.substringAfter的字符串表示来执行此操作:

StringUtils.substringAfter(value.toPlainString(), ".")

How about writing an extension method to extend this type. Simple method might multiply number until > 1

public int  trimLeadingZeroes(bigint num) {
    while (num < 1)
    {
       num = num * 10;
    }
       return num;
    }
import java.math.BigDecimal;
import java.math.RoundingMode;


public class RemoveZeroes {

    static final int SCALE = 10;    // decimal range 0.1 ... 0.0000000001
    static final String PADDING = "0000000000"; // SCALE number of zeroes

    public static void main(String [] arg) {

        BigDecimal [] testArray = {
            new BigDecimal(0.27),
            new BigDecimal(0.1),
            new BigDecimal(0.02),
            new BigDecimal(0.003),
            new BigDecimal(0.0000000001),
        };

        for (int i = 0; i < testArray.length; i++) {
            // normalize to the same scale
            BigDecimal b = testArray[i].setScale(SCALE, RoundingMode.FLOOR);
            // pad on the left with SCALE number of zeroes
            String step1 = PADDING + b.unscaledValue().toString();
            // remove extra zeroes from the left
            String step2 = step1.substring(step1.length() - SCALE);
            // remove extra zeroes from the right
            String step3 = step2.replaceAll("0+$", "");
            // print result
            System.out.println(step3);
        }

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM