Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the integer part and fractional part of a number in Swift

This is a super basic question, but, I can't seem to find an answer in Swift.

Question:

How do I get the whole integer part and fractional part (to the left and right of the decimal point respectively) of a number in Swift 2 and Swift 3? For example, for the number 1234.56789 —

How do I get the integer part 1234.56789 ?

How do I get the fractional part 1234.56789 ?

like image 356
user4806509 Avatar asked Jul 04 '17 15:07

user4806509


4 Answers

Convert your number into String later separate string from .

Try this:-

let number:Float = 123.46789
let numberString = String(number)
let numberComponent = numberString.components(separatedBy :".")
let integerNumber = Int(numberComponent [0])
let fractionalNumber = Int(numberComponent [1])
like image 182
Irshad Ahmad Avatar answered Oct 02 '22 01:10

Irshad Ahmad


You could do simple floor and truncating:

let value = 1234.56789
let double = floor(value) // 1234.0
let integer = Int(double) // 1234
let decimal = value.truncatingRemainder(dividingBy: 1) // 0.56789
like image 46
Thomas Avatar answered Oct 21 '22 15:10

Thomas


No need for extensions. Swift already has built in function for this.

let aNumber = modf(3.12345)
aNumber.0 // 3.0
aNumber.1 // 0.12345
like image 13
Just a coder Avatar answered Oct 21 '22 14:10

Just a coder


Swift 4.xm, 5.x complete solution: I credit @Thomas solution also I'd like to add few things which allow us to use separated parts in 2 string part. Especially when we want to use 2 different UILabel for main and decimal part of the number.

Separated integer and decimal label

Extension below is also managing number quantity of decimal part. I thought it might be useful.

UPDATE: Now, it is working perfectly with negative numbers as well!

public extension Double{
func integerPart()->String{
    let result = floor(abs(self)).description.dropLast(2).description
    let plusMinus = self < 0 ? "-" : ""
    return  plusMinus + result
}
func fractionalPart(_ withDecimalQty:Int = 2)->String{
    let valDecimal = self.truncatingRemainder(dividingBy: 1)
    let formatted = String(format: "%.\(withDecimalQty)f", valDecimal)
    let dropQuantity = self < 0 ? 3:2
    return formatted.dropFirst(dropQuantity).description
}
like image 13
Trevor Avatar answered Oct 21 '22 14:10

Trevor