NSNumberFormatter PercentStyle decimal places - swift

I'm using Swift
let myDouble = 8.5 as Double
let percentFormatter = NSNumberFormatter()
percentFormatter.numberStyle = NSNumberFormatterStyle.PercentStyle
percentFormatter.multiplier = 1.00
let myString = percentFormatter.stringFromNumber(myDouble)!
println(myString)
Outputs 8% and not 8.5%, how would I get it to output 8.5%? (But only up to 2 decimal places)

To set the number of fraction digits use:
percentFormatter.minimumFractionDigits = 1
percentFormatter.maximumFractionDigits = 1
Set minimum and maximum to your needs. Should be self-explanatory.

With Swift 5, NumberFormatter has an instance property called minimumFractionDigits. minimumFractionDigits has the following declaration:
var minimumFractionDigits: Int { get set }
The minimum number of digits after the decimal separator allowed as input and output by the receiver.
NumberFormatter also has an instance property called maximumFractionDigits. maximumFractionDigits has the following declaration:
var maximumFractionDigits: Int { get set }
The maximum number of digits after the decimal separator allowed as input and output by the receiver.
The following Playground code shows how to use minimumFractionDigits and maximumFractionDigits in order to set the number of digits after the decimal separator when using NumberFormatter:
import Foundation
let percentFormatter = NumberFormatter()
percentFormatter.numberStyle = NumberFormatter.Style.percent
percentFormatter.multiplier = 1
percentFormatter.minimumFractionDigits = 1
percentFormatter.maximumFractionDigits = 2
let myDouble1: Double = 8
let myString1 = percentFormatter.string(for: myDouble1)
print(String(describing: myString1)) // Optional("8.0%")
let myDouble2 = 8.5
let myString2 = percentFormatter.string(for: myDouble2)
print(String(describing: myString2)) // Optional("8.5%")
let myDouble3 = 8.5786
let myString3 = percentFormatter.string(for: myDouble3)
print(String(describing: myString3)) // Optional("8.58%")

When in doubt, look in apple documentation for minimum fraction digits and maximum fraction digits which will give you these lines you have to add before formatting your number:
numberFormatter.minimumFractionDigits = 1
numberFormatter.maximumFractionDigits = 2
Also notice, your input has to be 0.085 to get 8.5%. This is caused by the multiplier property, which is for percent style set to 100 by default.

Related

When rounding swift double it shows different numbers

When I got two numbers, like 5.085 and 70.085. My code rounds the first number to 5.09, but the second one it goes to 70.08. For some reason, when making let aux1 = aux * 100 the value goes to 7008.49999999. Any one have the solution to it?
Here is my code:
let aux = Double(value)!
let aux1 = aux * 100
let aux2 = (aux1).rounded()
let number = aux2 / 100
return formatter.string(from: NSNumber(value: number))!
If you want to format the Double by rounding it's fraction digits. Try't:
First, implement this method
func formatDouble(_ double: Double, withFractionDigits digits: Int) -> String{
let formatter = NumberFormatter()
formatter.maximumFractionDigits = digits
let string = formatter.string(from: (NSNumber(floatLiteral: double)))!
return string
/*if you want a Double instead of a String, change the return value and uncomment the bellow lines*/
//let number = formatter.number(from: string)!
//return number.doubleValue
}
after, you can call't that way
let roundedNumber = formatDouble(Double(value)!, withFractionDigits: 2)

Remove trailing numbers from String

I am receiving two kid of Doubles from JSON:
1.12 and 0.00007067999999
The second number switches automatically to scientific notation(
7.067e-05), so I'm using the function String(format:"%.8f", NUMBER) to make it 0.00007067, yes it works, but now my first number becomes 1.12000000.
How to clean trailing numbers?
I've tried with Swift - Remove Trailing Zeros From Double , but the %g format changes second number to scientific notation again, so %g is not an option. Any suggestions?
You can use NumberFormater and set minimum and maximum fraction digits:
let double1 = 1.12
let double2 = 0.00007067999999
let numberFormatter = NumberFormatter()
numberFormatter.minimumFractionDigits = 2
numberFormatter.maximumFractionDigits = 8
numberFormatter.minimumIntegerDigits = 1
numberFormatter.string(for: double1) ?? "" // "1.12"
numberFormatter.string(for: double2) ?? "" // "0.00007068"
if you would like to round the fraction digits down you can set the formatter rounding mode option to .down:
numberFormatter.roundingMode = .down
numberFormatter.string(for: double2) ?? "" // "0.00007067"

Rounding numbers in swift

In Swift, I need to be able to round numbers based on their value. If a number is whole, which just ".0" after it, I need to convert it to an integer, and if the number has digits after the decimal that is greater than 2 digits, I need to round it to 2 digits.
For example:
1.369352 --> 1.37
7.75 --> 7.75
2.0 --> 2
How can I check my numbers and round them according to these rules?
Something like this should be good?
func formatNumber (number: Double) -> String? {
let formatter = NSNumberFormatter()
formatter.maximumFractionDigits = 2
let formattedNumberString = formatter.stringFromNumber(number)
return formattedNumberString?.stringByReplacingOccurrencesOfString(".00", withString: "")
}
formatNumber(3.25) // 3.25
formatNumber(3.00) // 3
formatNumber(3.25678) // 3.26
this function returns a string of the result needed.
func roundnumber(roundinput:Double) ->String{
var roundoutputint=0
var roundoutputfloat=0.0
if (roundinput - floor(roundinput) < 0.00001) { // 0.000001 can be changed depending on the level of precision you need
//integer
roundoutputint = Int(round(roundinput))
return String(roundoutputint)
}
else {
//not integer
//roundoutputfloat=round(10 * roundinput) / 10
return String(format:"%.2f",roundinput)
}
}
for example:
roundnumber(1.3693434) //returns "1.37"
roundnumber(7.75) //returns "7.75"
roundnumber(2.0) // returns "2"

Formatting decimal places with unknown number

I'm printing out a number whose value I don't know. In most cases the number is whole or has a trailing .5. In some cases the number ends in .25 or .75, and very rarely the number goes to the thousandths place. How do I specifically detect that last case? Right now my code detects a whole number (0 decimal places), exactly .5 (1 decimal), and then reverts to 2 decimal spots in all other scenarios, but I need to go to 3 when it calls for that.
class func getFormattedNumber(number: Float) -> NSString {
var formattedNumber = NSString()
// Use the absolute value so it works even if number is negative
if (abs(number % 2) == 0) || (abs(number % 2) == 1) { // Whole number, even or odd
formattedNumber = NSString(format: "%.0f", number)
}
else if (abs(number % 2) == 0.5) || (abs(number % 2) == 1.5) {
formattedNumber = NSString(format: "%.1f", number)
}
else {
formattedNumber = NSString(format: "%.2f", number)
}
return formattedNumber
}
A Float uses a binary (IEEE 754) representation and cannot represent
all decimal fractions precisely. For example,
let x : Float = 123.456
stores in x the bytes 42f6e979, which is approximately
123.45600128173828. So does x have 3 or 14 fractional digits?
You can use NSNumberFormatter if you specify a maximum number
of decimal digits that should be presented:
let fmt = NSNumberFormatter()
fmt.locale = NSLocale(localeIdentifier: "en_US_POSIX")
fmt.maximumFractionDigits = 3
fmt.minimumFractionDigits = 0
println(fmt.stringFromNumber(123)!) // 123
println(fmt.stringFromNumber(123.4)!) // 123.4
println(fmt.stringFromNumber(123.45)!) // 123.45
println(fmt.stringFromNumber(123.456)!) // 123.456
println(fmt.stringFromNumber(123.4567)!) // 123.457
Swift 3/4 update:
let fmt = NumberFormatter()
fmt.locale = Locale(identifier: "en_US_POSIX")
fmt.maximumFractionDigits = 3
fmt.minimumFractionDigits = 0
print(fmt.string(for: 123.456)!) // 123.456
You can use %g to suppress trailing zeros. Then I think you do not need to go through the business of determining the number of places. Eg -
var num1:Double = 5.5
var x = String(format: "%g", num1) // "5.5"
var num2:Double = 5.75
var x = String(format: "%g", num2) // "5.75"
Or this variation where the number of places is specified. Eg -
var num3:Double = 5.123456789
var x = String(format: "%.5g", num3) // "5.1235"
My 2 cents ;) Swift 3 ready
Rounds the floating number and strips the trailing zeros to the required minimum/maximum fraction digits.
extension Double {
func toString(minimumFractionDigits: Int = 0, maximumFractionDigits: Int = 2) -> String {
let formatter = NumberFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.minimumFractionDigits = minimumFractionDigits
formatter.maximumFractionDigits = maximumFractionDigits
return formatter.string(from: self as NSNumber)!
}
}
Usage:
Double(394.239).toString() // Output: 394.24
Double(394.239).toString(maximumFractionDigits: 1) // Output: 394.2
If you want to print a floating point number to 3 decimal places, you can use String(format: "%.3f"). This will round, so 0.10000001 becomes 0.100, 0.1009 becomes 0.101 etc.
But it sounds like you don’t want the trailing zeros, so you might want to trim them off. (is there a way to do this with format? edit: yes, g as #simons points out)
Finally, this really shouldn’t be a class function since it’s operating on primitive types. Better to either make it a free function, or perhaps extend Double/Float:
extension Double {
func toString(#decimalPlaces: Int)->String {
return String(format: "%.\(decimalPlaces)g", self)
}
}
let number = -0.3009
number.toString(decimalPlaces: 3) // -0.301

How to use println in Swift to format number

When logging-out a float in Objective-C you can do the following to limit your output to only 2 decimal places:
float avgTemp = 66.844322156
NSLog (#"average temp. = %.2f", avgTemp);
But how do you do this in Swift?
And how do you escape other characters in println in Swift?
Here's a regular Swift println statement:
println ("Avg. temp = \(avgTemp)")
So how do you limit decimal places?
Also, how do you escape double-quotes in println?
Here's the shortest solution I found thus far:
let avgTemp = 66.844322156
println(NSString(format:"%.2f", avgTemp))
Its like the swift version of NSString's stringWithFormat
Everything about the format of a number as a string can be adjusted using a NSNumberFormatter:
let nf = NSNumberFormatter()
nf.numberStyle = NSNumberFormatterStyle.DecimalStyle
nf.maximumFractionDigits = 2
println(nf.stringFromNumber(0.33333)) // prints 0.33
You can escape quotes with a backslash
println("\"God is dead\" -Nietzsche")
Println() is deprecated.
var avgTemp = 66.844322156
print("average temp. = (round(avgTemp*100)/100)") // average temp. = 66.84
//or
print(NSString(format:"average temp. = %.2f", avgTemp))) // average temp. = 66.84
avgTemp = 66.846322156
print(String(format:"average temp. = %.2f", avgTemp)) // average temp. = 66.85
If you need to print floating point numbers often with a certain precision, you could extend Float and Double with convenience methods. For example, for 2 significant figure precision:
// get Float or Double with 2 significant figure precision
var numberFormatter = NSNumberFormatter()
extension Float {
var sf2:String {
get {
numberFormatter.numberStyle = NSNumberFormatterStyle.DecimalStyle
numberFormatter.maximumSignificantDigits = 2
return numberFormatter.stringFromNumber(self)!
}
}
}
extension Double {
var sf2:String {
get {
numberFormatter.numberStyle = NSNumberFormatterStyle.DecimalStyle
numberFormatter.maximumSignificantDigits = 2
return numberFormatter.stringFromNumber(self)!
}
}
}
Then when you need to print things:
let x = 5.23325
print("The value of x is \(x.sf2)")