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

Friday, August 12, 2022

[FIXED] How can I round UP to two decimal places in Swift?

 August 12, 2022     decimal, math, rounding, swift     No comments   

Issue

I'm using the below code and I'm trying to get my 'outputvalue' to round UP to two decimal places on button press.

I've found various different methods online and tried to incorporate them but with no luck. Could some point me in the right direction please?

If the calculation comes out to 164.98001 then I'd like the answer to display 164.99.

edit - I don't think this is a duplicate question as my question relates to rounding UP all numbers.

@IBAction func buttoncalc(_ sender: Any) {
    total.isHidden = false
    let firstValue = Double(text1.text!)
    let secondValue = Double(text2.text!)
    let thirdValue = Double(text3.text!)
    let forthValue = Double(text4.text!)


    if firstValue != nil && secondValue != nil && thirdValue != nil && forthValue != nil {

    let outputvalue = Double(((firstValue! * secondValue!)/1000)*0.5)*(thirdValue! - forthValue!)
    total.text = "£ \(outputvalue)"

    } else {
    total.text = nil
    }
}

Solution

You can use NumberFormatter to get formatted number as String. Just limit number of decimal places to 2 and set roundingMode to up

let formatter = NumberFormatter()
formatter.roundingMode = .up
formatter.minimumFractionDigits = 2
formatter.maximumFractionDigits = 2
let number = 164.98001
print(formatter.string(from: NSNumber(value: number)) ?? "") // 164.99

To improve your logic even more, you can set formatter's numberStyle and locale

formatter.numberStyle = .currency
formatter.locale = Locale(identifier: "en_UK")
// £164.99

Your specific usage:

let string = formatter.string(from: NSNumber(value: outputvalue)) ?? ""
total.text = string


Answered By - Robert Dresler
Answer Checked By - Dawn Plyler (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