Skip to content

Convert numbers between string, float, double, decimal

This code demonstrates the convertion of a float number string to various numeric data types, including Float, Double, Decimal, NSDecimalNumber in Swift Language.

The resulting values are then printed so you can see the precision loss of different data types.

swift
var str = "0.99999999"

if let f = Float(str) {
    print("str:\(str) Float:\(f)")
}
if let d = Double(str) {
    print("str:\(str) Double:\(d)")
}
if let dec = Decimal(string: str) {
    print("str:\(str) Decimal:\(dec)" )
    
}
let nsdec = NSDecimalNumber(string: str)
print("str:\(str) NSDecimalNumber:\(nsdec) NSDecimalNumber.floatValue:\(nsdec.floatValue) NSDecimalNumber.doubleValue:\(nsdec.doubleValue)")

Results:

StringFloatDoubleDecimalNSDecimalNumber.floatValue.doubleValue
0.90.90.90.90.90.90.9
0.990.990.990.990.990.990.99
0.9990.9990.9990.9990.9990.9990.999
0.99990.99990.99990.99990.99990.99990.9998999999999999
0.999990.999990.999990.999990.999990.999990.99999
0.9999990.9999990.9999990.9999990.9999990.9999990.9999990000000001
0.99999990.99999990.99999990.99999990.99999990.99999990.9999998999999999
0.999999991.00.999999990.999999990.999999991.00.9999999899999998
0.9999999991.00.9999999990.9999999990.9999999991.00.9999999990000001
0.99999999991.00.99999999990.99999999990.99999999991.00.9999999999
0.999999999991.00.999999999990.999999999990.999999999991.00.9999999999900002
0.9999999999991.00.9999999999990.9999999999990.9999999999991.00.9999999999989999
0.99999999999991.00.99999999999990.99999999999990.99999999999991.00.0.9999999999999002
0.999999999999991.00.999999999999990.999999999999990.999999999999991.00.99999999999999
0.9999999999999991.00.9999999999999990.9999999999999990.9999999999999991.00.9999999999999991
0.99999999999999991.00.99999999999999990.99999999999999990.99999999999999991.01.0
0.999999999999999991.01.00.999999999999999990.999999999999999991.01.0
0.9999999999999999991.01.00.9999999999999999990.9999999999999999991.01.0