Riscy
Riscy

Reputation: 915

printf signed integer and decimal point, issue with negative sign

dsPIC33, XC16 compiler.

The dat1 is signed INT16, where it has value of 16434 and -16434 to be printed to 164.34 and -164.34.

printf("---: +/-180 from North   %d.%02d (deg)\n",(dat1/100),(dat1%100));

With dat1=164.34, I get

---: +/-180 from North -164.34 (deg)

With dat1=-164.34, I get

---: +/-180 from North -164.-34 (deg)

==> How to get rid of minus sign on '-.34'?

Upvotes: 0

Views: 254

Answers (1)

harper
harper

Reputation: 13690

Your statement is almost correct, except you want to get rid off the sign in the second number. You can use this statement.

printf("---: +/-180 from North   %d.%02d (deg)\n", dat1/100, abs(dat1)%100);

Edit: Thanks to @chux.

The code above works in the desired range from -180.00 to 180.0 degrees. When you need a more general approach you should move the modulo operation before calling abs().

Postponing the abs() avoids problems at INT_MIN since abs(INT_MIN) may give unexpected results. Then the code should be:

printf("---: +/-180 from North   %d.%02d (deg)\n", dat1 / 100, abs(dat1 % 100));

Upvotes: 1

Related Questions