Checking If a Double Value Is an Integer - Swift

Checking if a double value is an integer - Swift

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

Display Double as Int if it is a whole number in Swift

Convert Double into Number and then to String if u want to show it on label

let i = 1.0
let j = 1.2345

// Value in String

let a = NSNumber(value: j).stringValue // "1.2345"
let b = NSNumber(value: i).stringValue // "1"

// Value in Double

let c = NSNumber(value: i).doubleValue // 1.0
let d = NSNumber(value: j).doubleValue // 1.2345

check string is int or double , with extension in swift 3

As @MartinR said, check if the string can be converted to an Int or a Double:

extension String  {
var isnumberordouble: Bool { return Int(self) != nil || Double(self) != nil }
}

print("1".isnumberordouble) // true
print("1.2.3".isnumberordouble) // false
print("1.2".isnumberordouble) // true

@MartinR raises a good point in the comments. Any value that converts to an Int would also convert to a Double, so just checking for conversion to Double is sufficient:

extension String  {
var isnumberordouble: Bool { return Double(self) != nil }
}

Handling leading and trailing whitespace

The solution above works, but it isn't very forgiving if your String has leading or trailing whitespace. To handle that use the trimmingCharacters(in:) method of String to remove the whitespace (requires Foundation):

import Foundation

extension String {
var isnumberordouble: Bool { return Double(self.trimmingCharacters(in: .whitespaces)) != nil }
}

print(" 12 ".isnumberordouble) // true

Check if string is a valid double value in Swift

It is indeed more efficient not to create a number formatter every time we do a conversion:

extension String {
struct NumFormatter {
static let instance = NumberFormatter()
}

var doubleValue: Double? {
return NumFormatter.instance.number(from: self)?.doubleValue
}

var integerValue: Int? {
return NumFormatter.instance.number(from: self)?.intValue
}
}

Swift check if NSNumber is Double

You can get type of the number stored using low-level CoreFoundation API:

extension NSNumber {
var type: CFNumberType {
return CFNumberGetType(self as CFNumber)
}
}

And then you can use it.

Your plus function gonna be something like that:

extension NSNumber {
func plus(other: NSNumber) -> NSNumber {
switch type {
case .sInt8Type, .charType:
return NSNumber(value: self.int8Value + other.int8Value)
case .sInt16Type, .shortType:
return NSNumber(value: self.int16Value + other.int16Value)
case .sInt32Type, .longType:
return NSNumber(value: self.int32Value + other.int32Value)
case .sInt64Type, .longLongType:
return NSNumber(value: self.int64Value + other.int64Value)
case .float32Type, .floatType:
return NSNumber(value: self.floatValue + other.floatValue)
case .float64Type, .doubleType:
return NSNumber(value: self.doubleValue + other.doubleValue)
case .intType, .cfIndexType, .nsIntegerType:
return NSNumber(value: self.intValue + other.intValue)
case .cgFloatType:
switch MemoryLayout<CGFloat>.size {
case 4:
return NSNumber(value: self.floatValue + other.floatValue)
default:
return NSNumber(value: self.doubleValue + other.doubleValue)
}
}
}
}

How can you check if a string is a valid double in Swift

You can extend Double adding a new custom initializer

extension Double {
init?(myCustomFormat:String) {
guard let
standardDouble = Double(myCustomFormat),
firstChar: Character? = myCustomFormat.characters.first,
lastChar: Character? = myCustomFormat.characters.last
where firstChar != "." && lastChar != "."
else { return nil }
self = standardDouble
}
}

This initializer does create a Double only if:

  1. the built initializer does succeed and the last
  2. the first char of the input String is not a "."
  3. the last char of the input String is not a "."

Examples

Double(myCustomFormat:"1.") // nil
Double(myCustomFormat:".1") // nil
Double(myCustomFormat:"Hello") // nil
Double(myCustomFormat:"1.1") // 1.1
Double(myCustomFormat:"1") // 1

Check if number is decimal with swift

If you round the number down (which you can do by using the floor function), and then subtract it from the original number, you will get the difference between the two.

if (number - floor(number) > 0.000001) { // 0.000001 can be changed depending on the level of precision you need
// decimal
}

Edit --

My original answer recommended calculating the difference between the number and its floored equivalent to see if there were any units after the decimal points. However, as later described, there may be a rounding error which causes the representation of a value in memory to be slightly different than what it's actually meant to be.

For example, 3.0 could be represented as 3.00000000000001, and therefore the number - floor(number) > 0 would return true, even though it should've theoretically returned false as the offset would be 0.00000000000001.

Therefore please use @jessy's answer below.

Testing if a Decimal is a whole number in Swift

Thanks for the comments! Here is what I am using now.

extension Decimal {
var isWholeNumber: Bool {
return self.isZero || (self.isNormal && self.exponent >= 0)
}
}


Related Topics



Leave a reply



Submit