1

I am trying to convert 1.06 to 106 by multiplying by 100 but the answer comes 105, I do not know why. Variable ver can be any decimal in this format x.xx

float ver = 1.06;
int vers = ver * 100;
vm[0] = (vers / 100U) % 10;
vm[1] = (vers / 10U) % 10;
vm[2] = (vers / 1U) % 10;
Serial.println(vers);  

Could you let me know what I am doing wrong or maybe I have to do something else.

1 Answer 1

5

1.06 is not a float. The closest float is 1.059999942779541015625. If you multiply that by 100 you get a number that, again, is not a float. Rounding to the nearest float yields 105.99999237060546875, which is the result of the expression ver * 100, and just one ULP short of 106. Yes, floating point computations do quite usually involve rounding steps.

Casting to an int implicitly rounds towards zero, and you get 105, which is the correct result. Correct according to the rules of IEEE 754 arithmetics.

You may want to round() to the nearest integer before the cast.

Variable ver can be any decimal in this format x.xx

No, a float cannot be “any decimal” in this format. Floats are stored in binary, and most decimal numbers (numbers that can be written with a finite number of decimal digits) cannot be written in binary with a finite number of bits.

Except for a few values (namely the multiples of 0.25), ver can only store an approximation of the decimal number.

1
  • Thanks for the answer, now it make sense.
    – Shahreza
    Sep 30, 2021 at 19:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.