如何获得数字小数部分的长度? [英] How to get the length of a numbers fraction part?

查看:65
本文介绍了如何获得数字小数部分的长度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何求十进制数的小数部分的长度或位数?

How do I find out the length or the number of digits of the fraction part of a decimal number?

我可以看到一些方法,例如像这样的字符串:

I can see a few aproaches, e.g. with Strings like this one:

public static int getNumberOfFractionDigits(Number number) {
    Double fractionPart = number.doubleValue() - number.longValue();
    return fractionPart.toString().length() - 2;
}

但是确定长度的最佳方法是什么?

But what is the best way to determine the length?

如果我使用字符串,我可以想象一些问题,例如因为区域设置和数字格式可能因系统而异.有没有好的计算方法?也许没有迭代?

I could imagine some problems if I use Strings, e.g. because the locale and number format may be different from system to system. Is there a nice way to calculate it? Maybe without iteration?

提前致谢.

推荐答案

那是我最好的实现:

public class NumberHandler {

    private static NumberFormat formatter = NumberFormat.getInstance(Locale.ENGLISH);

    static {
        formatter.setMaximumFractionDigits(Integer.MAX_VALUE);
        formatter.setGroupingUsed(false);
    }

    public static int getFractionLength(double doubleNumber) {
        String numberStr = formatter.format(doubleNumber);
        int dotIndex = numberStr.indexOf(".");
        if (dotIndex < 0) {
            return 0;
        } else {
            return numberStr.length() - (dotIndex + 1);
        }
    }

}

效果不佳,可能不完美,但其他选项更糟.

Not effective, probably not perfect, but the other options was worse.

这篇关于如何获得数字小数部分的长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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