NSNumberFormatter for degrees' values - swift

Is there any proper implementation for 0°00'00.00" format?
NSNumberFormatter supports only groupingSeparator and decimalSeparator.
Or not?

There is no degree-minute-second formatter in Foundation but it's not too hard to roll your own. Here's my crude attempt:
class DegreeFormatter : NumberFormatter {
func string(from degree: Double) -> String {
var remaining = degree
let degree = remaining.rounded(.towardZero)
remaining -= degree
remaining *= 60.0
let minute = remaining.rounded(.towardZero)
remaining -= minute
remaining *= 60
let seconds = remaining
return "\(Int(degree))°\(Int(minute))'\(self.string(from: seconds as NSNumber)!)"
}
}
let formatter = DegreeFormatter()
formatter.maximumFractionDigits = 2
print(formatter.string(from: 1.23456789)) // 1°14'4.44
You can customize it further to include custom degree symbols, whether to include the second, what units are allowed, etc.

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)

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

Convert decimal to hours:minutes:seconds

I am storing numbers in a MySQL DB as doubles so I can get min, max and sums.
I have a decimal number 1.66777777778 which equals 01:40:04 however I am wanting to be able to convert this decimal in to hour:minutes:seconds in Swift so I can display the value as 01:40:04 however I don't know how.
I have done some searching but most results are calculators without explanation.
I have this function to convert to decimal:
func timeToHour(hour: String, minute:String, second:String) -> Double
{
var hourSource = 0.00
if hour == ""
{
hourSource = 0.00
}
else
{
hourSource = Double(hour)!
}
let minuteSource = Double(minute)!
let secondSource = Double(second)!
let timeDecimal: Double = hourSource + (minuteSource / 60) + (secondSource / 3600)
return timeDecimal
}
but need one to go back the other way.
Thanks
Try:
func hourToString(hour:Double) -> String {
let hours = Int(floor(hour))
let mins = Int(floor(hour * 60) % 60)
let secs = Int(floor(hour * 3600) % 60)
return String(format:"%d:%02d:%02d", hours, mins, secs)
}
Basically break each component out and concatenate them all together.

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.