Velocity Reviews > Java > Decimal Places

# Decimal Places

Bharat Bhushan
Guest
Posts: n/a

 08-08-2003
Hi,

How can I store upto 10 decimal places in a variable. I have tried this code
with float and double datatype but it only prints 1.0

public class tmp
{
static void main(String[] args)
{
float a1 = 0.0000000000f;
a1 = 2/3;
System.out.print(a1);
}
}

It only prints 0.0 whereas I would like it to print 0.6666666666

- Bharat.

Tim Slattery
Guest
Posts: n/a

 08-08-2003
"Bharat Bhushan" <(E-Mail Removed)> wrote:

>Hi,
>
>How can I store upto 10 decimal places in a variable. I have tried this code
>with float and double datatype but it only prints 1.0

Floats are approximations. Your decimal fraction is converted to
binary, which yields inexactnesses, then stuffed it into a double or
float which can lose significant digits.

If you need precision, especially if you need precision in decimal

--
Tim Slattery
http://www.velocityreviews.com/forums/(E-Mail Removed)

Lee Weiner
Guest
Posts: n/a

 08-08-2003
In article <cMQYa.6006\$(E-Mail Removed)>, "Bharat Bhushan" <(E-Mail Removed)> wrote:
>Hi,
>
>How can I store upto 10 decimal places in a variable. I have tried this code
>with float and double datatype but it only prints 1.0
>
>public class tmp
>{
> static void main(String[] args)
> {
> float a1 = 0.0000000000f;
> a1 = 2/3;
> System.out.print(a1);
> }
>}
>
>It only prints 0.0 whereas I would like it to print 0.6666666666

In this particular case, the problem is your division. When Java divides an
integer by an integer, it performs integer division and drops the remainder.
Try: a1 = 2/3.0; and see what happens.

Lee Weiner
lee AT leeweiner DOT org