I want to make a floating point number that has only one decimal point. I have separate integers for both side. Ex:

int n1 = 8;

int n2 = 2;

I want to make 8.2 as float value using separate integers. Please give me a solution.

closed as off-topic by Juraj, sempaiscuba, per1234, gre_gor, Greenonline Dec 1 at 2:43

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "This question does not appear to be about Arduino, within the scope defined in the help center." – Juraj, sempaiscuba, per1234, gre_gor, Greenonline
If this question can be reworded to fit the rules in the help center, please edit the question.

up vote 4 down vote accepted

Seems too simple:

float x = n1 + n2 * 0.1;

Is there a trick?

Edit: The method proposed by Michel Keijzers, namely

float x = n1 + n2 / 10.0;

(I removed the redundant casts) can be slightly more accurate, but takes longer to compute, because division is significantly slower than multiplication on the Uno. Computing n2/10.0 always yields the correctly rounded result, namely the float that best approximates the exact mathematical result. On the other hand, n2*0.1 involves two rounding operations: one at compile time, in the representation of 0.1 (which is not an exact float), another at run time, which rounds the result of the multiplication. If n2 is between 0 and 8, you end up getting the correctly rounded result anyway, just as with n2/10.0. However, if n2 is 9, then

  • n2*0.1 yields 0.900000035762786865234375 (error ≈ 3.6e-8)
  • n2/10.0 yields 0.89999997615814208984375 (error ≈ -2.4e-8)

The former carries a rounding error 1.5 larger than the latter.

  • Thanks. Its a real trick. – user119o Nov 30 at 9:36
float x = (float) n1 + (float) (n2 / 10.0);

This works only if the value of n2 has 1 digit. Otherwise the following make it smaller until n2 gets below 1.0:

float x = (float) n1;

float f2 = (float) n2;
while (f2 >= 1.0)
   f2 /= 10.0;
x = n1 + f2;
  • 1
    Its working without problem. Thanks – user119o Nov 30 at 9:43

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