简体   繁体   English

如何在不删除Java中尾随零的情况下找到双精度数字小数点后的长度?

[英]how to find length after decimal point of a double number without removing trailing zeroes in java?

Suppose you have a double number say Double d = 12.123223800000 . 假设您有一个双Double d = 12.123223800000数,例如Double d = 12.123223800000 How can we find length of number from decimal point till the end including all trailing zeroes in it. 我们如何找到从小数点到末尾的数字长度,其中包括所有尾随零。

Double d = 12.123223800000;
String t = d.toString();

Here it's removing all the trailing zeroes from double number. 这是从双数中删除所有尾随零。

Are you able to assign the string directly? 您可以直接分配字符串吗? Java primitives don't keep trailing zeros because of their binary representation, yet in Mathematics trailing zeros are meaningless .. and so on. Java原语由于二进制表示而不会保留尾随零,但是在数学中尾随零是没有意义的..依此类推。 This sample would kinda work 此示例会有点儿工作

Double d = 12.123223800000;
String str = "12.123223800000"; // d.toString() won't work here
int length = str.length() - str.indexOf(".");
System.out.println(String.format("%."+ length +"f", d)); 
//prints out - 12.1232238000000

There's no difference between 12.123223800000 and 12.1232238 . 12.12322380000012.1232238之间没有区别。 The trailing zeros are removed while you initialize it to Double. 将尾部零初始化为Double时,它们将被删除。 If you still need such solution 如果您仍然需要这样的解决方案

String d = "12.123223800000";
System.out.println((d.length()-d.indexOf("."))-1);

This should work: 这应该工作:

String text = Double.toString(Math.abs(d))
int decimalPlaces = text.length()  - text.indexOf('.') - 1;

There is no way to get the trailing zeros counted because they don't affect the mathematical value of your double figure. 无法计算尾随零,因为它们不影响双精度数字的数学值。 Edit: Except you assign your value directly to a string. 编辑:除了您直接将值分配给字符串。 With Javas primitve types, it is not possible 使用Java primitve类型,这是不可能的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM