How to reduce decimal points in UnitConverter? [duplicate] - swift

This question already has an answer here:
Limit formatted Measurement to 2 digits
(1 answer)
Closed 4 years ago.
I write simple code to convert temperature units from kelvin to fahrenheit or celsius.
I want to remove decimal points like an 71.5999999999957 results.
Do you have any simple solution?
import Foundation
var base: Double = 295.14999999999998
let kelvinTemperature = Measurement.init(value: base, unit: UnitTemperature.kelvin)
let fahrenheitTemperature = kelvinTemperature.converted(to: .fahrenheit)
let celsiusTemperature = kelvinTemperature.converted(to: .celsius)
print(celsiusTemperature)
print(fahrenheitTemperature)
results :
22.0 °C
71.5999999999957 °F

I found solution.
import Foundation
var base: Double = 295.14999999999998
let kelvinTemperature = Measurement.init(value: base, unit: UnitTemperature.kelvin)
let fahrenheitTemperature = kelvinTemperature.converted(to: .fahrenheit)
let celsiusTemperature = kelvinTemperature.converted(to: .celsius)
let numFormatter = NumberFormatter()
numFormatter.maximumFractionDigits = 2
let measureFormatter = MeasurementFormatter()
measureFormatter.numberFormatter = numFormatter
let fahrenheit = measureFormatter.string(from: fahrenheitTemperature)
print(celsiusTemperature)
print(fahrenheit)

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

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

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

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))

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.