-2

I am new with swift and I need help. I want to get first two digits after the decimal point, for example -

1456.456214 -> 1456.45 
35629.940812 -> 35629.94

without rounding the double to next one.

Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
Martin
  • 1

3 Answers3

1

Try the below code

let num1 : Double = 1456.456214
let num2 : Double = 35629.940812

let numberFormatter = NumberFormatter()
numberFormatter.minimumFractionDigits = 2
numberFormatter.maximumFractionDigits = 2
numberFormatter.roundingMode = .down        
let str = numberFormatter.string(from: NSNumber(value: num1))
let str2 = numberFormatter.string(from: NSNumber(value: num2))

print(str)
print(str2)

Output

1456.45
35629.94
chirag90
  • 2,211
  • 1
  • 22
  • 37
0

To keep it a double you can do

let result = Double(Int(value * 100)) / 100.0

or, as @vacawama pointed out, use floor instead

let result = floor(value * 100) / 100
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
-2
extension Double {
func truncate(places : Int)-> Double
{
    return Double(floor(pow(10.0, Double(places)) * self)/pow(10.0, Double(places)))
}

}

and use this like as;

let ex: Double = 35629.940812
print(ex.truncate(places: 2)) //35629.94

let ex1: Double = 1456.456214
print(ex1.truncate(places: 2)) //1456.45
sanjeev
  • 150
  • 3
  • Please don't duplicate [another answer](https://stackoverflow.com/a/35946921/1630618), especially one from the linked duplicate question. – vacawama Sep 12 '19 at 13:17