Problem on getting digits in a double variable

倾然丶 夕夏残阳落幕 提交于 2019-12-05 13:03:30

Doubles and floats and operations on then are not exact so there will always bee slight errors compared with algebraic calculations. If you are using cosines etc then you will always have to deal with these rounding errors which any book or web text on numerical analysis should describe. If you are using simple aritmetic operations look at java.lang.BigDecimal

For details on how floating point values are stored.see What Every Computer Scientist Should Know About Floating-Point Arithmetic

toString().length() should solve it
remeber to substract the '.' if it is there and shouldn't be counted

This is how I implemented mine, Simple converting to String when the double was to big returned String with an exponential representation. i.e 20000000 would return 2.0E+7, and the split would then split it from here resulting in wrong count. I used to BigDecimal and to toPlainString() method

protected int countDecimalDigits(Double d) {
    BigDecimal deci = BigDecimal.valueOf(d);
    int integerPlaces = 0;
    int decimalPlaces = 0;
    String text = deci.toPlainString();

    String[] integerDecimalSplit = text.split("\\.");
    if (null != integerDecimalSplit[0]) {
        integerPlaces = integerDecimalSplit[0].length();
    }
    if (integerDecimalSplit.length > 1) {
        decimalPlaces = integerDecimalSplit[1].length();
    }
    return integerPlaces + decimalPlaces;
}

It's a rounding issue. I would use Strings, count the characters, and decide what figures are to be counted significant.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!