'Swift: String from float without rounding the values
It is recommended to round the decimals but i am facing an scenario where i just need to cut down the precision.
Output: 15.96 to 16.0
- Desired output: 15.96 to 15.9
Codes:
var value: AnyObject = dict.valueForKey("XXX")!
var stringVal = NSString(format:"%.1f", value.floatValue)
I thought this will be simple but found tricky. Your thoughts on this is highly appreciated.
Solution 1:[1]
Use a NSNumberFormatter and configure its rounding mode accordingly:
let formatter = NSNumberFormatter()
formatter.maximumFractionDigits = 1
formatter.roundingMode = .RoundDown
let s = formatter.stringFromNumber(15.96)
// Result: s = "15.9"
Solution 2:[2]
Try using this:
var test : AnyObject = "15.96"
var rounded_down = floorf(test.floatValue * 10) / 10;
print(rounded_down)
Solution 3:[3]
Here's an updated answer in Swift 5 based on @Clafou 's answer. You can use it as an extension to any data type. Example
extension Double {
func cutToDecimalPlace(_ decimalPlaces: Int) -> String{
let formatter = NumberFormatter()
formatter.maximumFractionDigits = decimalPlaces
formatter.roundingMode = .down
return formatter.string(from: NSNumber(value: self)) ?? ""
}
}
And you can call it like this
let priceValueString = "24.124"
let updatedPriceValue = priceValueString.doubleValue.cutToDecimalPlace(1)
Output will be 24.1
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Clafou |
| Solution 2 | |
| Solution 3 |
