开发者

How to get the list of digits in the scale representing the BigDecimal

I have 3 BigDecimal objects 9.1, 9.12, 9.123 and I am looking to get the number of digits in the scale which would 开发者_开发百科be 1, 2 and 3 for the above decimals. How do I get this?

Should I get the scale and then do String.length or is there a simpler way?


BigDecimal bd = new BigDecimal("1.2");
bd.scale();//this will return 1

BigDecimal bd = new BigDecimal("1.23");
bd.scale();//this will return 2

BigDecimal bd = new BigDecimal("1.234");
bd.scale();//this will return 3

See Also

  • JavaDoc


you can also find it with this way

    public static int scale(BigDecimal bd){
           int length = bd.toString().length();
           int longValueLength = Long.toString(bd.longValue()).length();
           int scale =  length - longValueLength - 1;
           return scale;

    }

    public static void main(String[] args) throws IOException {

           BigDecimal bd1 = new BigDecimal("9.123");
           BigDecimal bd2 = new BigDecimal("9.12233");

           System.out.println(scale(bd1)); // 3
           System.out.println(scale(bd2)); // 5
     }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜