gpt4 book ai didi

java - 查找 double 值的小数位数的有效方法

转载 作者:行者123 更新时间:2023-11-30 02:30:39 25 4
gpt4 key购买 nike

我想找到一种有效的方法来确保小数位数双不超过三。

double num1 = 10.012; //True
double num2 = 10.2211; //False
double num2 = 10.2; //True

目前,我所做的只是使用正则表达式拆分和计数索引。像下面这样。

String[] split = new Double(num).toString().split("\\.")
split[0].length() //num of decimal places

有没有一种有效或更好的方法来做到这一点,因为我会调用它功能很多吗?

最佳答案

如果您想要一个解决方案,以一种与将 double 转换为字符串的最终结果相一致的方式告诉您该信息,那么效率并没有真正发挥作用;你基本上必须转换为字符串并检查。结果是, double 型完全有可能包含一个在数学上(例如)万位中具有(例如)非零值的值,但在转换为字符串时则不会。这就是 IEEE-754 double 二进制浮点的乐趣:从字符串表示中获得的位数仅是区分该值与其相邻可表示值所需的位数。来自 the Double docs :

How many digits must be printed for the fractional part of m or a? There must be at least one digit to represent the fractional part, and beyond that as many, but only as many, more digits as are needed to uniquely distinguish the argument value from adjacent values of type double. That is, suppose that x is the exact mathematical value represented by the decimal representation produced by this method for a finite nonzero argument d. Then d must be the double value nearest to x; or if two double values are equally close to x, then d must be one of them and the least significant bit of the significand of d must be 0.

但是如果您不关心这一点,并且假设将值范围限制为 long 是可以的,那么您可以执行以下操作:

private static boolean onlyThreePlaces(double v) {
double d = (double)((long)(v * 1000)) / 1000;
return d == v;
}

...它的内存开销应该比 String 往返要少。

但是,如果该方法和 Double.toString(double) 的结果没有出现相当多的次数,我会感到惊讶出于上述原因,按小数点后的数字进行匹配。

<小时/>

在对该问题的评论中,您说过(当我询问值范围时):

Honestly I'm not sure. I'm dealing with prices; For starters, I'll assume 0-200K

使用double来表示财务值通常不是一个好主意。如果由于内存问题您不想使用 BigDecimal,请选择您的精度并根据您的值范围使用 int 或 long 。例如,如果您只需要精确到便士的精度,则可以使用乘以 100 的值(例如,2000 是 Ⓠ20 [或者您使用的任何货币,我使用 Ⓠ 表示 quatloos ])。如果您需要精确到千分之一(如您的问题所示),请乘以 100000(例如,2000000 是 Ⓠ20)。如果您需要更高的精度,请选择更大的乘数。即使您达到万分之一便士(乘数:10000000),使用 long ,您的范围也为 Ⓠ-922,337,203,685 到 Ⓠ922,337,203,685。

这有一个额外的好处,它使检查更容易:只需一个直接的 %。如果您的乘数是 10000000(一分钱的十万分之一),则只需 value % 10000 != 0 来识别无效乘数(或 value % 10000 == 0 来识别有效)。

long num1 = 100120000;  // 10.012   => true
// 100120000 % 10000 is 0 = valid
long num2 = 102211000; // 10.2211 => false
// 102211000 % 10000 is 1000 = invalid
long num3 = 102000000; // 10.2 => true
// 102000000 % 10000 is 0 = valid

关于java - 查找 double 值的小数位数的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44370395/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com