1

I am trying to divide two numbers in java - more specifically I have the fraction 800/9177 and want to convert it to a double or float or w/e. My problem is when I try to get the value of the fraction, I get 0.

Anybody knows how to do this?

my code:

double dt = 800/9177;
float ft = 800/9177;
double dw = 800/122;
System.out.println("dt : " + dt + " ft: " + ft + " dw " + dw + " 800/9177 " + (800/9177));

it prints dt: 0 ft: 0 dw : 6.0 800/9177 0 so all my fractions except for dw is 0.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
user1090614
  • 2,575
  • 6
  • 22
  • 27

3 Answers3

3

The simplest is

double dt = 800.0/9177;

or

double dt = (double) 800 / 9177;
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

Using the data type int will result in an int with loss of data. Use double and float data types from the start like this

double dt = 800/9177.0;
float ft = 800/9177.0f;
double dw = 800/122.0;

A double number rcan be specified like this

double d = (double) 123;
double d = 123.0; //default floating point type is double. use f for float 
double d = 123d;
juergen d
  • 201,996
  • 37
  • 293
  • 362
0
double dt = 800D / 9177;

If you divide two ints, you get an integer division. To get a double division, one of the operands must be a double.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255