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

Thursday, August 11, 2022

[FIXED] How do I round the Decimal type?

 August 11, 2022     decimal, swift3     No comments   

Issue

Using Swift3 and still getting the hang of things. I'm using the Decimal type because it involves currency and I'm having a difficult time with getting the rounding to work. I've read through the NSDecimalNumberHandler documentation and the rounding function but don't quite understand how to get this to work. Essentially I just want all my Decimal types in this class to round to the hundredths spot when the calculation functions I've built run.

Can someone give me quick example of how to do this? Thanks!


Solution

Please check this :

This is using NSDecimalNumber & NSDecimalNumberHandler :

let decimalStr = NSDecimalNumber(string: "500.2595")
let decimalStrHandler = NSDecimalNumberHandler(roundingMode: .plain, scale: 3, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: false)
let roundedVal = decimalStr.rounding(accordingToBehavior: decimalStrHandler)
print(roundedVal) // prints 500.26

This is using NumberFormatter & Decimal :

extension Decimal {
    func roundDecimal() -> String {
        let formatter = NumberFormatter()
        formatter.minimumFractionDigits = 2
        return formatter.string(from: self as NSDecimalNumber)!
    }
}

You have to call like below :

let decimalStr = Decimal(string: "500.2595")!
print(decimalStr.roundDecimal()) // prints 500.26

let decimalFloat = Decimal(floatLiteral: 500.2595)
print(decimalFloat.roundDecimal())  // prints 500.26


Answered By - Vini App
Answer Checked By - Timothy Miller (PHPFixing Admin)
  • 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

1,216,969

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 © 2025 PHPFixing