Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Swift how do I display a percentage value rounded up or down with no decimal places

Tags:

swift

I thought this would be fairly straightforward, but I can't seem to work it out or find an existing question that's covers my situation.

Originally I set up a number of variables as follows:

var score :Int! = 0
var totalquestionsasked :Int! = 0
var percentagecorrect :Int! = 0

This got all my values calculating okay, but I ran into problems with the percentage.

My basic formula for the percentage is:

percentagecorrect = score / totalquestionsasked * 100

However, I couldn't get this to display when using the value in a text label.

So after some research, I changed my variables to this instead:

var score :Double = 0.0
var totalquestionsasked :Double = 0.0
var percentagecorrect :Double = 0.0

And still used the same formula for the percentage:

percentagecorrect = score / totalquestionsasked * 100

However, while this displayed okay, I didn't want all the decimal places. So after some more research I came across an extension in another question and adapted it for my application. My extension is:

extension Double {
    var roundTo0f: Double {return Double(round(1*self)/1) }
    var roundTo1f: Double {return Double(round(10*self)/10) }
    var roundTo2f: Double {return Double(round(100*self)/100)  }
    var roundTo3f: Double {return Double(round(1000*self)/1000) }
}

And I've tried using the extension as follows:

percentagecorrect = score / totalquestionsasked * 100
let percentagevalue: Double = percentagecorrect.roundTo0f
labelPercent.text = "\(percentagevalue)"

The end result is that this is pretty close to what I want. However it does still display the percentage to 1 decimal place. (As an aside, it's not accurate - what I mean is that if the score is 1 and the number of questions asked is 3, the above code displays the percentage as 33.0 instead of 33.3, but I digress)

What I'm actually wanting is the value to round up or down to the nearest whole number before displaying the value. In other words, what I want is

  • if the value is 33.3 for it to round down to 33 and display as 33
  • if the value is 66.6 for it to round up to 67 and display as 67

That is I want no decimal places at all in the displayed result. At present, it rounds up/down correctly but sill displays ".0" at the end. If this isn't possible, then I want it to display to one decimal place correctly.

I am new to programming and Swift is the first language I'm trying to learn, so maybe this is just a newbie mistake, but I really can't find what I'm doing wrong.

How do I get this to work?

like image 541
Monomeeth Avatar asked Feb 18 '16 23:02

Monomeeth


People also ask

How do you round off decimals in Swift?

Rounding Numbers in Swift By using round(_:) , ceil(_:) , and floor(_:) you can round Double and Float values to any number of decimal places in Swift.

How do you change a number to a percentage round?

To convert a decimal to a percentage, multiply by 100 (just move the decimal point 2 places to the right). For example, 0.065 = 6.5% and 3.75 = 375%. To find a percentage of a number, say 30% of 40, just multiply. For example, (30/100)(40) = 0.3 x 40 = 12.

How do you calculate percentage in Swift?

You need e/i*100 . @ChiefTwoPencils No, an income of 100 and expenses of 50 means the remaining percent is 0.5 or 50%.


Video Answer


3 Answers

You can use the built in round function and cast to an Int.

print(Int(round(33.3)))
print(Int(round(66.6)))

If you want an extension method to return a string, you can use this:

extension Double {
    func roundTo(decimalPlaces: Int) -> String {
        return NSString(format: "%.\(decimalPlaces)f", self) as String
    }
}
like image 128
totiDev Avatar answered Oct 16 '22 10:10

totiDev


In pure integer arithmetic,

var score : Int = ...
var totalquestionsasked : Int = ...
let percentagecorrect = (score * 200 + totalquestionsasked)/(2 * totalquestionsasked)

would do the trick.


How does this work? Computing the percentage as

(score * 100)/totalquestionsasked

truncates the result of the division towards zero. For the desired rounding behavior, we would have to compute

(score * 100)/totalquestionsasked + 1/2

in floating point arithmetic and then truncate the result to an integer. Combining terms give the expression

(score * 200 + totalquestionsasked)/(2 * totalquestionsasked)

which, when computed in integer arithmetic, gives the correct result.

like image 4
Martin R Avatar answered Oct 16 '22 11:10

Martin R


You can use the format specifier of NSString and add it to your Double extension as functions.

extension Double
{
  func roundTo0f() -> NSString
  {
    return NSString(format: "%.0f", self)
  }

  func roundTo1f() -> NSString
  {
    return NSString(format: "%.1f", self)
  }

  func roundTo2f() -> NSString
  {
    return NSString(format: "%.2f", self)
  }

  func roundToNf(n : Int) -> NSString
  {
    return NSString(format: "%.\(n)f", self)
  }
} 

let d : Double = 9.12
print(d.roundTo0f())
print(d.roundTo1f())
print(d.roundTo2f())
like image 2
Christian Abella Avatar answered Oct 16 '22 10:10

Christian Abella