Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: String from float without rounding the values

Tags:

ios

swift

  1. It is recommended to round the decimals but i am facing an scenario where i just need to cut down the precision.

  2. Output: 15.96 to 16.0

  3. 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.

like image 957
Yogesh Lolusare Avatar asked Jul 21 '15 14:07

Yogesh Lolusare


People also ask

How do you print a float with only 2 digits without rounding in Swift?

You might get a decent solution by using String(format: "%. 2f", weight >= 0 ? weight - 0.005 : weight + 0.005) but the real solution is to use NumberFormatter and choosing the rounding mode correctly (probably . down ).

How do I get only 2 decimal places in Swift?

The "%f" format string means "a floating point number," but "%. 2f" means "a floating-point number with two digits after the decimal point. When you use this initializer, Swift will automatically round the final digit as needed based on the following number.

How do you round a float to 2 decimal places in Swift?

Rounding Numbers in SwiftBy using round(_:) , ceil(_:) , and floor(_:) you can round Double and Float values to any number of decimal places in Swift.


1 Answers

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"
like image 144
Clafou Avatar answered Oct 30 '22 19:10

Clafou