Appearance
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)")
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:
String | Float | Double | Decimal | NSDecimalNumber | .floatValue | .doubleValue |
---|---|---|---|---|---|---|
0.9 | 0.9 | 0.9 | 0.9 | 0.9 | 0.9 | 0.9 |
0.99 | 0.99 | 0.99 | 0.99 | 0.99 | 0.99 | 0.99 |
0.999 | 0.999 | 0.999 | 0.999 | 0.999 | 0.999 | 0.999 |
0.9999 | 0.9999 | 0.9999 | 0.9999 | 0.9999 | 0.9999 | 0.9998999999999999 |
0.99999 | 0.99999 | 0.99999 | 0.99999 | 0.99999 | 0.99999 | 0.99999 |
0.999999 | 0.999999 | 0.999999 | 0.999999 | 0.999999 | 0.999999 | 0.9999990000000001 |
0.9999999 | 0.9999999 | 0.9999999 | 0.9999999 | 0.9999999 | 0.9999999 | 0.9999998999999999 |
0.99999999 | 1.0 | 0.99999999 | 0.99999999 | 0.99999999 | 1.0 | 0.9999999899999998 |
0.999999999 | 1.0 | 0.999999999 | 0.999999999 | 0.999999999 | 1.0 | 0.9999999990000001 |
0.9999999999 | 1.0 | 0.9999999999 | 0.9999999999 | 0.9999999999 | 1.0 | 0.9999999999 |
0.99999999999 | 1.0 | 0.99999999999 | 0.99999999999 | 0.99999999999 | 1.0 | 0.9999999999900002 |
0.999999999999 | 1.0 | 0.999999999999 | 0.999999999999 | 0.999999999999 | 1.0 | 0.9999999999989999 |
0.9999999999999 | 1.0 | 0.9999999999999 | 0.9999999999999 | 0.9999999999999 | 1.0 | 0.0.9999999999999002 |
0.99999999999999 | 1.0 | 0.99999999999999 | 0.99999999999999 | 0.99999999999999 | 1.0 | 0.99999999999999 |
0.999999999999999 | 1.0 | 0.999999999999999 | 0.999999999999999 | 0.999999999999999 | 1.0 | 0.9999999999999991 |
0.9999999999999999 | 1.0 | 0.9999999999999999 | 0.9999999999999999 | 0.9999999999999999 | 1.0 | 1.0 |
0.99999999999999999 | 1.0 | 1.0 | 0.99999999999999999 | 0.99999999999999999 | 1.0 | 1.0 |
0.999999999999999999 | 1.0 | 1.0 | 0.999999999999999999 | 0.999999999999999999 | 1.0 | 1.0 |