Add and format leading zero's in a string [duplicate] - swift

This question already has an answer here:
Including zeros in front of an integer [duplicate]
(1 answer)
Closed 6 years ago.
I want to show a number in my app, and to keep it pretty, display leading zeros to make the layout even.
For example
000 500 / 500 000
001 000 / 500 000
100 350 / 500 000
I get the first number from an Int, and I want to format it into a string.
Is there a neat way to assure that a number is always six digits, and also get the range of the leading zeros to format them differently?

NSNumberFormatter has everything that you needs:
let formatter = NumberFormatter()
formatter.minimumIntegerDigits = 6
formatter.numberStyle = .decimal
print(formatter.string(from: 500)!)
print(formatter.string(from: 1000)!)
print(formatter.string(from: 100_350)!)

How about this?
String extension:
extension String {
func substring(startIndex: Int, length: Int) -> String {
let start = self.startIndex.advancedBy(startIndex)
let end = self.startIndex.advancedBy(startIndex + length)
return self[start..<end]
}
}
usage:
var a = 500
var s = "000000\(a)"
print(s.substring(s.characters.count - 6, length: 6))
a = 500000
s = "000000\(a)"
print(s.substring(s.characters.count - 6, length: 6))
a = 50
s = "000000\(a)"
print(s.substring(s.characters.count - 6, length: 6))

Related

How to obtain precision of two numbers after the decimal point but without rounding the double in SWIFT [duplicate]

This question already has answers here:
How to truncate decimals to x places in Swift
(10 answers)
Closed 3 years ago.
I am new with swift and I need help. I want to get first two digits after the decimal point, for example -
1456.456214 -> 1456.45
35629.940812 -> 35629.94
without rounding the double to next one.
Try the below code
let num1 : Double = 1456.456214
let num2 : Double = 35629.940812
let numberFormatter = NumberFormatter()
numberFormatter.minimumFractionDigits = 2
numberFormatter.maximumFractionDigits = 2
numberFormatter.roundingMode = .down
let str = numberFormatter.string(from: NSNumber(value: num1))
let str2 = numberFormatter.string(from: NSNumber(value: num2))
print(str)
print(str2)
Output
1456.45
35629.94
To keep it a double you can do
let result = Double(Int(value * 100)) / 100.0
or, as #vacawama pointed out, use floor instead
let result = floor(value * 100) / 100
extension Double {
func truncate(places : Int)-> Double
{
return Double(floor(pow(10.0, Double(places)) * self)/pow(10.0, Double(places)))
}
}
and use this like as;
let ex: Double = 35629.940812
print(ex.truncate(places: 2)) //35629.94
let ex1: Double = 1456.456214
print(ex1.truncate(places: 2)) //1456.45

Convert pounds to pound decimals in Swift (2.2)

How can I convert pounds to pound decimals?
For instance if the user enters 1.8 lbs, I would like to be able to convert it to 1.5 lbs so I can do some calculations.
The code below has two issues.
1- It only works when the user enters less then 10 (e.g 1.9) ounces since I'm multiplying the ounces by 10.
2- It only returns the decimal ounces, It does not return the whole number (pounds).
func poundsToDecimals(pounds:Double)->Double{
let ounces = Double(pounds % 1)
let decimals = ounces / 16 * 10
return decimals
}
print(poundsToDecimals(1.4)) //prints... 0.25
To solve your first problem try converting it the number into a String and then split it up like so:
func poundsToDecimals(pounds: Double) -> Double {
let numberAsString = String(pounds)
var numbers = numberAsString.components(separatedBy: ["."])
let seperatedPounds = Double(numbers[0])!
let ounces = Double(numbers[1])!
let decimals = ounces / 16 * 10
return decimals
}
Can you please specify your second problem further. if you want to return more then one value you usally do it like this.
func poundsToDecimals(pounds: Double) -> (Double, Double) {
let numberAsString = String(pounds)
var numbers = numberAsString.components(separatedBy: ["."])
let seperatedPounds = Double(numbers[0])!
let ounces = Double(numbers[1])!
let decimals = ounces / 16 * 10
return (decimals, seperatedPounds)
}
Hope that helps

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

NSNumberFormatter PercentStyle decimal places

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.