programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Convert double (primitive) value to String

Ranch Hand
Posts: 73
Hi

I have a scenario where i need to know the number of digits after decimal point of a double value.

Lets say
i have

Now i would want to write a code to know how many digits the double value has after decimal point(i.e .)
which in this case is 4.

I tried with

but this gives me result as 0.0 and hence the

comes as 1.

Prashant

Java Cowboy
Sheriff
Posts: 16082
88
This is not possible in the way you think.

A double is just a number. It doesn't have a specified number of digits after the decimal point. 0.000 is exactly the same as 0.0 or 0.00000000 or 0. It's just zero.

but this gives me result as 0.0 and hence the
comes as 1.

That is really strange, because "0.0" is 3 characters, not 1.

If you want to format a number with a specified number of decimals after the decimal point, you have to specify that at the place you're converting the number to a string. The number of decimals is not some property of the number itself.

Bartender
Posts: 10575
66

What you want can't be done with Double/double or Float/float, because the literal 0.000 is identical to 0.0 (and so is its binary form).

What you can do is use a BigDecimal with its String constructor, viz:
BigDecimal bd = new BigDecimal("0.000");
because that will retain the number of places after the decimal point.

Winston

Ranch Hand
Posts: 73
Thanks a lot for the reply Winston..

However my problem is that i have that 0.000 value in double and not in String
so can not really make use of the solution provided by you.. is there any way other than this?

Thanks
Prashant

Jesper de Jong
Java Cowboy
Sheriff
Posts: 16082
88

Prashant Langade wrote:However my problem is that i have that 0.000 value in double and not in String

No, you don't. You have a double variable that has the value zero. Zero is zero and is exactly the same as 0, 0.0, 0.000, 0.000000000 or however many zeroes you bother to write.

If you do this:

then a and b have exactly the same value. It is impossible to know with how many decimal digits you wrote it in your source code, because there is no difference. The number of zeroes you wrote after the decimal point is not a property of the number that you can determine later on.

Winston Gutkowski
Bartender
Posts: 10575
66

Prashant Langade wrote:However my problem is that i have that 0.000 value in double and not in String

What Jesper said.

However, at some point you must have decided that you wanted 3 decimal places in the number; and the only way to store that value and retain that information is to use BigDecimal.

Winston