PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, July 20, 2022

[FIXED] How to separate integral part and fractional part in Swift? An how to transform fractional part into Int

 July 20, 2022     double, integer, swift     No comments   

Issue

I separated fractional part, but now I need to make that part as Int.

For example:

0.5 -> 5
0.63 -> 63


let a1 = 2.5
let a2 = 7.63
let a3 = 8.81
let a4 = 99.0
let a1Frac = a1.truncatingRemainder(dividingBy: 1)
let a2Frac = a2.truncatingRemainder(dividingBy: 1)
let a3Frac = a3.truncatingRemainder(dividingBy: 1)
let a4Frac = a4.truncatingRemainder(dividingBy: 1)

Solution

First you should use Swift Decimal type if you would like to preserve your fractional digits precision. Second to get its fraction value you can check this post. Once you have your decimal fractions all you need is to get their significand value:

extension Decimal {
    func rounded(_ roundingMode: NSDecimalNumber.RoundingMode = .bankers) -> Decimal {
        var result = Decimal()
        var number = self
        NSDecimalRound(&result, &number, 0, roundingMode)
        return result
    }
    var whole: Decimal { self < 0 ? rounded(.up) : rounded(.down) }
    var fraction: Decimal { self - whole }
}

let a1 = Decimal(string: "2.5")!
let a2 = Decimal(string: "7.63")!
let a3 = Decimal(string: "8.81")!
let a4 = Decimal(string: "99")!

let a1Frac = a1.fraction  // 0.5
let a2Frac = a2.fraction  // 0.63
let a3Frac = a3.fraction  // 0.81
let a4Frac = a4.fraction  // 0

let a1significand = a1Frac.significand  // 5
let a2significand = a2Frac.significand  // 63
let a3significand = a3Frac.significand  // 81
let a4significand = a4Frac.significand  // 0

If you need to convert your Decimal values to Int you can simply cast it to NSDecimalNumber and get its intValue or add those extensions to your project to add the same NSDecimalNumber functionality to Swift Decimal type:

extension Decimal {
    var decimalNumber: NSDecimalNumber { self as NSDecimalNumber}
    var intValue: Int { decimalNumber.intValue }
}

a1significand.intValue  // 5
a2significand.intValue  // 63
a3significand.intValue  // 81
a4significand.intValue  // 0


Answered By - Leo Dabus
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing