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

Wednesday, August 10, 2022

[FIXED] How to round decimal places in swift 2

 August 10, 2022     decimal, rounding, swift, swift2, xcode     No comments   

Issue

Trying to output the total of three number values from a dictionary and then adding HST of 13% to the total. However, the calculations print out as $13.5261 with four decimals places. How do I cut out the end decimal places, so it's $13.52? Or is there a way to round it, so it's $13.53

import UIKit 


 var menu = ["Coke": 1.99, "Coffee": 3.99, "Water": 5.99]

 var hst = 1.13

 var total = hst * (menu["Coke"]! + menu["Coffee"]! + menu["Water"]!)


 print("The total for your order is
 $\(total)")

Solution

The usual – and most versatile – way is NSNumberFormatter

let menu = ["Coke": 1.99, "Coffee": 3.99, "Water": 5.99]

let hst = 1.13

let total = hst * (menu["Coke"]! + menu["Coffee"]! + menu["Water"]!)

let formatter = NSNumberFormatter()   
formatter.maximumFractionDigits = 2
let roundedTotal = formatter.stringFromNumber(total)!

print("The total for your order is $\(roundedTotal)")


Answered By - vadian
Answer Checked By - Willingham (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