This question already has an answer here:
- How to test if a double is an integer 12 answers
I have a double value which I have to display at my UI. Now the condition is that the decimal value of double = 0 eg. - 14.0 In that case I have to show only 14 on my UI. Also, the max limit for characters is 5 here.
eg.- 12.34 the integer value can be no bigger than 2 digits and so is the decimal value for our double.
What could be the best way of doing this?
Compare two values: the normal double, and the double after
floor
ing it. If they are the same value, there is no decimal component.All Integers are modulo of 1. So below check must give you the answer.
You probably want to round the double to 5 decimals or so before comparing since a double can contain very small decimal parts if you have done some calculations with it.
If you are using C++ i don't think there is a round-function, so you have to implement it yourself like in: http://www.cplusplus.com/forum/general/4011/
Use number formatter to format the value, as required. Please check this.
Interesting little problem. It is a bit tricky, since real numbers, not always represent exact integers, even if they are meant to, so it's important to allow a tolerance.
For instance tolerance could be 1E-6, in the unit tests, I kept a rather coarse tolerance to have shorter numbers.
None of the answers that I can read now works in this way, so here is my solution:
And the unit test, to make sure it works:
either ceil and floor should give the same out out put
or simply check for equality with double value
or