Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do my floats insist on staying integers?

I am reading in several integers, which represent the year, julian day, hour, and minutes. I am trying to convert them to fractional days.

int YYYY, JJJ, HH, MM;

float datenumber = (YYYY*360.0f)+(JJJ*1.0f)+((HH*1.0f)+(MM/60.0f))/24.0f;

Using the values of 2001, 083, 22, 32 I should get a result of 724043.939. Instead I get 724044.

I have all the ints cast as floats. Why do they stay as integers?

edit Yes, I was displaying the output with cout. setprecision resolved the problem, thank you.

like image 409
RuQu Avatar asked Jan 30 '26 14:01

RuQu


2 Answers

The problem is not in your number or your calculation. It is only in the way you are displaying it. cout has decided that 6 digits is enough for you. Use setprecision if you want more.

std::cout << std::setprecision(10) << datenumber;

demo

like image 154
Benjamin Lindley Avatar answered Feb 01 '26 05:02

Benjamin Lindley


You need to do TWO things:

  1. Set your precision to the max (cout.setprecision(16))
  2. Convert to double (double dateNumber and YYYY*360.0)
like image 39
Jacob Avatar answered Feb 01 '26 04:02

Jacob