How to limit decimal places?

1
printf("%.3f", &resp);

I'm using the following line, however, when comparing with a number, it requires that it has the same decimal place as the originals, for example:

2.963258741 !=  2.963

Can you limit the houses for this comparison to be true?

    
asked by anonymous 01.12.2017 / 05:21

1 answer

1

Yes, but not the way you expect it to. You are using binary floating-point types , and comparisons are complicated. If it depends on accuracy, you need to use a fixed-point or floating-decimal type. Since C does not have native create a solution or tidy up a third-party library .

A "simpler" possibility is to turn this into integer to compare. You can multiply by 1000 to get the 3 houses you want and cast cast to int . Still not ideal because it may have rounding problems, to be exact you would have to deal with it.

A possibility without using a decimal type is to ask to enter the value without the comma, it fits in an integer.

Just note that if you manipulate integers you have to understand the scale, for sum and subtraction it is quiet, but for multiplication and division the number of houses changes and there you have to go back to the original number of houses. So a decimal type may be the most appropriate, it already treats it (although not always the way it needs, then it comes back to be manual).

There's a way to make comparison of float with approach , but I do not like it. Obviously you need to take care of the scale as well.

    
01.12.2017 / 10:43