0

Suppose you have a double number say 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.

soufrk
  • 825
  • 1
  • 10
  • 24

3 Answers3

0

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. 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
noobed
  • 1,329
  • 11
  • 24
  • I am using Double.toString(d) here. – Aayushi Tayal Jul 10 '18 at 12:48
  • @AayushiTayal Then I guess... there is no option to do so, unless you specify as a hard-coded constant how many digits after the decimal point you want. – noobed Jul 10 '18 at 13:54
  • if we'll take double value as a String input (String str = "12.123223800000"), then there are other options also, but don't know how we can convert double value to string without removing zeroes. – Aayushi Tayal Jul 11 '18 at 08:14
  • 1
    1. str = str.substring(str.indexOf(".")+1); int len = str.length()+1; .........2. There is another option also,we can parse the string to double value.. it'll give the number in exponential form.String str = "12.123223800000"; int length = str.length() - str.indexOf(".");Double d2 =Double.parseDouble(str.substring(str.indexOf('.')+1));String ch = d2.toString();int o = ch.indexOf('E'); String v=ch.substring(o+1); (The value of v will give you length after decimal point-1) – Aayushi Tayal Jul 11 '18 at 08:25
0

There's no difference between 12.123223800000 and 12.1232238. The trailing zeros are removed while you initialize it to Double. If you still need such solution

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

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

Seppl98
  • 21
  • 4