How to limit decimal place?

Asked

Viewed 1,990 times

1

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

I am using the following line, however, when comparing to a number, it requires that you have the same decimal place number as the original, for example:

2.963258741 !=  2.963

You have to limit the houses so that this comparison is true?

  • 1

    Possible duplicate of How to limit decimal places?

  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful to you. You can also vote on any question or answer you find useful on the entire site.

1 answer

1

There is, but not the way you expect. You’re 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. As C has no precise native create a solution or tidy up a third-party library.

A "simpler" possibility is to make this whole to compare. You can multiply by 1000 to get the 3 houses you want and make a cast for int. Still not ideal because it may have rounding problems, to be exact would have to treat this.

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

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

There’s a way to do the comparison of float approachably, but I don’t like it. Obviously need to take care of the scale too.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.