如何提取double / BigDecimal的小数位数 [英] How to extract fractional digits of double/BigDecimal
问题描述
假设我们有一个双倍值 12345.6789
(应该是动态的)
Say we have a double value of 12345.6789
(should be dynamic)
现在要求被分割了数字并获得十进制数字和小数位数,这将是:
Now the requirement is split the number and get the decimal digits and fractional digits, which would be:
double number = 12345.6789;
int decimal = 12345;
int fractional = 6789;
我得到了小数部分,但是你可以给出小数部分的提示吗?非常感谢。
I get the decimal part work out but could you please give a hint on the fractional part? Thanks a lot.
推荐答案
double number = 12345.6789; // you have this
int decimal = (int) number; // you have 12345
double fractional = number - decimal // you have 0.6789
这里的问题是小数部分不是在内存中写成0.6789,而是可能有某些偏移,可以这么说。例如 0.6789
可以存储为 0.67889999291293929991
。
The problem here is that the fractional part is not written in memory as "0.6789", but may have certain "offsets", so to say. For example 0.6789
can be stored as 0.67889999291293929991
.
我认为你的主要关注点不是获得小数部分,而是获得具有某种精度的小数部分。
I think your main concern here isn't getting the fractional part, but getting the fractional part with a certain precision.
如果您想获得分配给它的确切值,您可能需要考虑这个(虽然,这不是一个干净的解决方案):
If you'd like to get the exact values you assigned it to, you may want to consider this (altho, it's not a clean solution):
String doubleAsText = "12345.6789";
double number = Double.parseDouble(doubleAsText);
int decimal = Integer.parseInt(doubleAsText.split("\.")[0]);
int fractional = Integer.parseInt(doubleAsText.split("\.")[1]);
但是,正如我所说,这不是最有效和最干净的解决方案。
But, as I said, this is not the most efficient and cleanest solution.
这篇关于如何提取double / BigDecimal的小数位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!