检查BigDecimal是否为整数值 [英] Check if BigDecimal is integer value

查看:1251
本文介绍了检查BigDecimal是否为整数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以推荐一种高效方式来确定 BigDecimal 是否是数学意义上的整数值?

Can anyone recommend an efficient way of determining whether a BigDecimal is an integer value in the mathematical sense?

目前我有以下代码:

private boolean isIntegerValue(BigDecimal bd) {
    boolean ret;

    try {
        bd.toBigIntegerExact();
        ret = true;
    } catch (ArithmeticException ex) {
        ret = false;
    }

    return ret;
}

...但是如果有必要,我希望避免对象创建开销。以前我使用 bd.longValueExact()如果 BigDecimal 在内部使用其紧凑表示,则会避免创建对象,但是如果价值太大而不适合长期,显然会失败。

... but would like to avoid the object creation overhead if necessary. Previously I was using bd.longValueExact() which would avoid creating an object if the BigDecimal was using its compact representation internally, but obviously would fail if the value was too big to fit into a long.

任何帮助表示感谢。

推荐答案

根据 BigDecimal 值的来源/用法,可能会更快检查比例是否为< = 0。如果是,则它绝对是数学意义上的整数值。如果它> 0,那么 仍然是一个整数值,并且需要更昂贵的测试。

Depending on the source/usage of your BigDecimal values it might be faster to check if the scale <= 0 first. If it is, then it's definitely an integer value in the mathematical sense. If it is >0, then it could still be an integer value and the more expensive test would be needed.

这篇关于检查BigDecimal是否为整数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆