In Arduino how do I map an Integer value Float value or vice versa?

For example this simple script doesn't print out 1600 but still returns a float value of 0.00?

float a = 0.5;
a = map(a, 0.0, 1.0, 0.0, 3200.0);
  • 6
    \$\begingroup\$ As a side note: I really encourage you not to use Float at all in a CPU that doesn't support them in hardware. 99% of the time, fixed point math is enough and is a LOT faster. \$\endgroup\$
    – Blup1980
    Sep 26 '13 at 5:28

According to the Arduino pages:

The map() function uses integer math so will not generate fractions, when the math might indicate that it should do so. Fractional remainders are truncated, and are not rounded or averaged.

Therefore: Why not do it manually? float a = 0.5f * 3200.0f;


Found this one as replacement for the map function. Put this before the setup function and use mapfloat instead of map.

float mapfloat(float x, float in_min, float in_max, float out_min, float out_max)
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;

P.S.: This will take more flash rom ... but is doesn't matter, this solution is quick enaugh.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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