Decimal Places

B

Bharat Bhushan

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


Thanks for your time.

- Bharat.
 
T

Tim Slattery

Bharat Bhushan said:
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
fractions, use BigDecimal instead.
 
L

Lee Weiner

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top