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.

asked Sep 30, 2021 at 19:04

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.

answered Sep 30, 2021 at 19:12
1
  • Thanks for the answer, now it make sense. Commented Sep 30, 2021 at 19:14

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.