-2

Ok, kinda hard question to ask in a title, but here is what i want to do.

I want to basically detect if my float has a 0 after the . so that i can skip printing out the - for example - 1.0 and just print 1. Anyone have an idea as to how to do this ? I was thinking of some sort of modulus operator but cant really figure out a good way for that. Any help would be greatly appreciated.

Peter S
  • 39
  • 5
  • 1
    Does this answer your question: https://stackoverflow.com/questions/31390466/swift-how-to-remove-a-decimal-from-a-float-if-the-decimal-is-equal-to-0 – Kishan Bhatiya Feb 25 '20 at 11:27
  • yes it did. sorry, couldn't formulate that question to find it. thanks! – Peter S Feb 25 '20 at 17:50

2 Answers2

0

Try 'flooring' the double value then checking if it is unchanged:

let dbl = 2.0
let isInteger = floor(dbl) == dbl // true

Fails if it is not an integer

let dbl = 2.4
let isInteger = floor(dbl) == dbl // false
Abhishek R
  • 249
  • 1
  • 2
  • 11
0

Swift 3 and 4 :

var FloatVal : Float = 4.0


extension Float {
    var truncate: String {
       return self.truncatingRemainder(dividingBy: 1) == 0 ? String(format: "%.0f", self) : String(self)
    }
}

print("Value \(FloatVal.truncate)") // 4

Dhaval Raval
  • 594
  • 2
  • 7