Swift: string from float without rounding values

  • It is recommended to round decimal places, but I came across a script when I just need to reduce the accuracy.

  • Output: 15.96 to 16.0

  • Desired result: from 15.96 to 15.9

Codes:

var value: AnyObject = dict.valueForKey("XXX")!
  var stringVal = NSString(format:"%.1f", value.floatValue)

I thought it would be easy, but hard to find. Your thoughts on this are much appreciated.

+4
source share
4 answers

If you need to use a rounded number in future math exercises, you can use the following function:

func floorToPlaces(value:Double, places:Int) -> Double {
    let divisor = pow(10.0, Double(places))
    return floor(value * divisor) / divisor
}

Then you can call it with

var value: AnyObject = dict.valueForKey("XXX")!
var rounded = floorToPlaces(value.doubleValue, 1)
var stringVal = "\(rounded)"

What this actually did was the following:

15.96 * 10.0 = 159.6
floor(159.6) = 159.0
159.0 / 10.0 = 15.9

Caution: this help will not be in situations where you use scientific accuracy, i.e.

1.49850e0 --> 1.4e0 // (5 places --> 1 place)
1.39e10 --> 1.3e10 // (3 places --> 1 place)

It will treat all numbers as e0

+5

NSNumberFormatter :

let formatter = NSNumberFormatter()
formatter.maximumFractionDigits = 1
formatter.roundingMode = .RoundDown
let s = formatter.stringFromNumber(15.96)
// Result: s = "15.9"
+2

:

    var test : AnyObject = "15.96"
    var rounded_down = floorf(test.floatValue * 10) / 10;
    print(rounded_down)
0
let value: Float = 15.96
let stringVal = "\(value)"

print(stringVal)

: 15.96

-1
source

Source: https://habr.com/ru/post/1598905/


All Articles