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:
- the built initializer does succeed and the last
- the first char of the input
String
is not a"."
- 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
What's the Equivalent to String.Localizedstringwithformat(_:_:) for Swiftui's Localizedstringkey
Uicollectionview Compositionallayout Not Calling Uiscrolldelegate
Keyboard Overlaying Action Sheet in iOS 13.1 on Cncontactviewcontroller
Accessing Mkmapview Elements as Uiviewrepresentable in the Main (Contentview) Swiftui View
Confusion Due to Swift Lacking Implicit Conversion of Cgfloat
"Value of Type 'Authdataresult' Has No Member 'Uid'" Error
Can't Use Storyboard Custom Instantiated Window Controller
Trying to Stream Audio from Microphone to Another Phone via Multipeer Connectivity
Bool Being Seen as Int When Using Anyobject
Swiftui: How to Implement a Custom Init With @Binding Variables
Warning: Initialization of 'Unsafebufferpointer<T>' Results in a Dangling Buffer Pointer
Working with C Strings in Swift, Or: How to Convert Unsafepointer<Cchar> to Cstring
Turn Off Xcode's Unused Variable Warnings While Typing
Swiftui: Prevent Image() from Expanding View Rect Outside of Screen Bounds
Simultaneous Gesture Recognition for Specific Gestures
Converting Swift Array to Cfarray in Xcode 8 (Swift 3)