sergionni
sergionni

Reputation: 13510

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

Upvotes: 4

Views: 5604

Answers (9)

beny23
beny23

Reputation: 35018

You could use the string representation of value (a BigDecimal) and StringUtils.substringAfter to do this:

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

Upvotes: 1

Ashkan Aryan
Ashkan Aryan

Reputation: 3534

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, i.e. it'll be 023456 for the above example.

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

Upvotes: 1

Michael M.
Michael M.

Reputation: 467

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);
        }

    }
}

Upvotes: 0

A.H.
A.H.

Reputation: 66263

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?

Upvotes: 1

yahh
yahh

Reputation: 1195

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

Upvotes: 1

Pablo Grisafi
Pablo Grisafi

Reputation: 5047

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

Upvotes: 1

Dan MacBean
Dan MacBean

Reputation: 1925

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"; 
}

Upvotes: 10

Jon Skeet
Jon Skeet

Reputation: 1500465

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...)

Upvotes: 1

JBone
JBone

Reputation: 3203

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;
    }

Upvotes: 0

Related Questions