Getting the decimal part of a double in Swift
I’m trying to separate the decimal and integer parts of a double in swift. I’ve tried a number of approaches but they all run into the same issue…
let x:Double = 1234.5678 let n1:Double = x % 1.0 // n1 = 0.567800000000034 let n2:Double = x - 1234.0 // same result let n3:Double = modf(x, &integer) // same result
Is there a way to get 0.5678 instead of 0.567800000000034 without converting to the number to a string?
4 Solutions Collect From Internet About “Getting the decimal part of a double in Swift”
Without converting it to a string, you can round up to a number of decimal places like this:
let x:Double = 1234.5678 let numberOfPlaces:Double = 4.0 let powerOfTen:Double = pow(10.0, numberOfPlaces) let targetedDecimalPlaces:Double = round((x % 1.0) * powerOfTen) / powerOfTen
Your output would be
You can use
1 as the divider.
Returns the remainder of this value divided by the given value using truncating division.
let myDouble1: Double = 12.25 let myDouble2: Double = 12.5 let myDouble3: Double = 12.75 let remainder1 = myDouble1.truncatingRemainder(dividingBy: 1) let remainder2 = myDouble2.truncatingRemainder(dividingBy: 1) let remainder3 = myDouble3.truncatingRemainder(dividingBy: 1) remainder1 -> 0.25 remainder2 -> 0.5 remainder3 -> 0.75
Float since it has less precision digits than
let x:Double = 1234.5678 let n1:Float = Float(x % 1) // n1 = 0.5678
You can use:
x % floor(abs(x))
- Best way to create a numeric pad as seen in Apples telephone app
- How to check Resolution, bitrate of video in iOS
- Connecting Team Foundation Server (TFS) with Xcode
- MPNowPlayingInfoCenter not reacting properly when pausing playback
- Iphone app with device UDID
- hide / show tab bar when push / back. swift
- xcode/ios: trying to copy files to caches folder on install
- Creating UIImage with renderingMode in Swift
- How do I add auto-complete comment in XCode (Swift)?
- Hide UISearchBar Cancel Button
- Why does instantiating a UIFont in an iphone unit test cause a crash?
- Cut a UIImage into a circle
- Setting the zoom level for a MKMapView
- How to track down cause of SIGABRT
- How to use image as button in ionic