删除 BigDecimal 的前导零和分隔符

发布于 2024-12-04 17:18:46 字数 447 浏览 2 评论 0原文

我们的应用程序可以获取以下数字:

0.1
0.02
0.003

等等。

这些值被我们的代码视为BigDecimal,就我们使用货币进行操作而言。

Web UI 上有一个表单,用户应该在其中查看价格的这些浮动部分,转换为以下部分:

1
02
003

问题是,如何修剪输入中的前导 分隔符价格。也许 BigDecimal 类有标准方法,如 trimLeadingZeroes(),但找不到任何标准方法。

更新: 仅修剪前导零和分隔符

例如:

1 is 0.1

27 is 0.27

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

你的往事 2024-12-11 17:18:46

像这样的东西吗?

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

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"; 
}
放手` 2024-12-11 17:18:46

您是否尝试过调用 BigDecimal.unscaledValue?缺点是 0.13 将是 13,而您可能想要 1.3...这有点难以判断。如果你能举出更多的例子,那真的会有帮助。

(如果一开始的值是 1000,那么这种方法也会失败 - 你最终会得到 1...)

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

情话墙 2024-12-11 17:18:46

是否可以像这样做一样简单:

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

所以如果你制作

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

它将打印

0.1
0.02
0.003

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
末蓝 2024-12-11 17:18:46

当你必须处理分割某些东西时,最好使用字符串来完成它。

首先,您只需将 bigdecimal 转换为字符串

String s=bd.toPlainString();

然后您只需将其拆分,

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

现在 String s2 包含分隔符后的数字

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

雨轻弹 2024-12-11 17:18:46

BigDecimalString 的转换:

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

结果是:

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

该代码直接处理任何数字,并且仅考虑小数部分。
它还可以优雅地处理“0.0”。

这是您想要的转换吗?

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?

不一样的天空 2024-12-11 17:18:46

这是执行此操作的另一种简单方法 - 假设您的输入是 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) : "";

这将给出您在 bd3 中查找的确切结果,即上面的示例中它将是 023456。

由于最后一行的条件,它对于整数也可以正常工作,即 1 将返回“”

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

站稳脚跟 2024-12-11 17:18:46

您可以使用 value 的字符串表示形式(BigDecimal)和 StringUtils.substringAfter 执行此操作:

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

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

StringUtils.substringAfter(value.toPlainString(), ".")
无可置疑 2024-12-11 17:18:46

如何编写一个扩展方法来扩展此类型?简单的方法可能会将数字相乘直到> 1

public int  trimLeadingZeroes(bigint num) {
    while (num < 1)
    {
       num = num * 10;
    }
       return num;
    }

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;
    }
深者入戏 2024-12-11 17:18:46
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);
        }

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

    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文