I want my Double to display as an Int, if the value is an integer - otherwise as a Double.
Example;
var Value = Double()
.
Value = 25.0 / 10.0
Now I want Value
to display 2.5
(when inserted to label)
.
Value = 20.0 / 10.0
Now I want Value
to display 2
- and NOT 2.0
Working on a calculator on Swift 4, I treated the number variables as String so I could display them on screen and converted them to Double for the calculations, then convert them back to String to display the result. When the result was an Int I didn't want the .0 to be displayed as well so I worked this out and it was pretty simple
so result is the variable in Double format, if divided by 1 it gives us 0 (perfect division means its an Int), I convert it in Int.
To display numbers as text, use
NSNumberFormatter()
. You can set itsminimumFractionDigits
property to zero:If you want a decimal period, independent of the user's locale, then add
Swift 3:
I like dasblinkenlight's and vacawama's answers, but also want to contribute another one: Using NSNumberFormatter
result:
The most important advantage: It is localized. On german devices it will show 2,5 instead of 2.5, just as it would be expected by a german speaking user.
One classic way is to establish a value for epsilon which represents your tolerance for considering a value close enough to an
Int
:One approach is to obtain the fractional part using
%
operator, and check if it is zero: