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

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

Related

NSNumberFormatter and .floor roundingMode

Can someone tell me why this happening?
let formatter = NumberFormatter.init()
formatter.numberStyle = .decimal
formatter.usesGroupingSeparator = false
formatter.roundingMode = .floor
formatter.minimumFractionDigits = 2
formatter.maximumFractionDigits = 2
let v = 36
let scale = 10
let float = formatter.string(from: NSNumber(value: Float(v) / Float(scale)))!
let double = formatter.string(from: NSNumber(value: Double(v) / Double(scale)))!
print(float) // 3.59
print(double) // 3.60
When I use Float the result is 3.59 (wrong result in my opinion) and when I use Double the result is 3.60.
I know it is something related to .floor roundingMode, but i don't fully understand the reason.
If you would like to preserve your fraction digits precision it is better to use Swift native Decimal type. That's what it is. You can use the Decimal init(sign: FloatingPointSign, exponent: Int, significand: Decimal) initializer and use your scale exponent and your value significand. Just make sure to negate its value:
extension SignedInteger {
var negated: Self { self * -1 }
}
let v = 36
let scale = 10
let sign: FloatingPointSign = v >= 0 ? .plus : .minus
let exponent = Decimal(scale).exponent.negated
let significand = Decimal(v).significand
let decimal = Decimal.init(sign: sign, exponent: exponent, significand: significand)
let formatted = formatter.string(for: decimal) // "3.60"

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)

How to reduce decimal points in UnitConverter? [duplicate]

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)

Odd division result in swift [duplicate]

I'm trying to make a math app with different equations and formulas but I'm trying to circle sector but i just wanted to try to divide the input value by 360 but when I do that it only says 0 unless the value is over 360. I have tried using String, Double and Float with no luck I don't know what I'm doing is wrong but down here is the code. I'm thankful for help but I have been sitting a while and searched online for an answer with no result I might have been searching with the wrong search.
if graderna.text == ""{
}
else{
var myInt: Int? = Int(graderna.text!) // conversion of string to Int
var myInt2: Int? = Int(radien.text!)
let pi = 3.1415926
let lutning = 360
let result = (Double(myInt! / lutning) * Double(pi))
svar2.text = "\(result)"
}
Your code is performing integer division, taking the integer result and converting it to a double. Instead, you want to convert these individual integers to doubles and then do the division. So, instead of
let result = (Double(myInt! / lutning) * Double(pi))
You should
let result = Double(myInt!) / Double(lutning) * Double(pi)
Note, Double already has a .pi constant, so you can remove your pi constant, and simplify the above to:
let result = Double(myInt!) / Double(lutning) * .pi
Personally, I’d define myInt and lutning to be Double from the get go (and, while we’re at it, remove all of the forced unwrapping (with the !) of the optionals):
guard
let text = graderna.text,
let text2 = radien.text,
let value = Double(text),
let value2 = Double(text2)
else {
return
}
let lutning: Double = 360
let result = value / lutning * .pi
Or, you can use flatMap to safely unwrap those optional strings:
guard
let value = graderna.text.flatMap({ Double($0) }),
let value2 = radien.text.flatMap({ Double($0) })
else {
return
}
let lutning: Double = 360
let result = value / lutning * .pi
(By the way, if you’re converting between radians and degrees, it should be 2π/360, not π/360.)
You are dividing an Int by an Int.
Integer division rounds to the nearest integer towards zero. Therefore for example 359 / 360 is not a number close to 1, it is 0. 360 / 360 up to 719 / 360 equals 1. 720 / 360 to 1079 / 360 equals 2, and so on.
But your use of optionals is atrocious. I'd write
let myInt = Int(graderna.text!)
let myInt2 = Int(radien.text!)
if let realInt = myInt, realInt2 = myInt2 {
let pi = 3.1415926
let lutning = 360.0
let result = Double (realInt) * (pi / lutning)
svar2.text = "\(result)"
}
In the line let result = (Double(myInt! / lutning) * Double(pi)) you cast your type to double after dividing two integers so your result will always be zero. You have to make them doubles before division.
let result = (Double(myInt!) / Double(lutning)) * Double(pi))
If you want the value should be correct, then try as
let division = ((Float(V1) / Float(V2)) * Float(pi))

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