-1

Example value : 3.00035358. i am trying to convert double value to string

Method 1:

let num = NSNumber(value:self)
let formatter : NumberFormatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.minimumFractionDigits = 4
let str = formatter.string(from: num)!
return str

method2 :

extension Double {

    var stringWithoutZeroFraction: String {
        return truncatingRemainder(dividingBy: 1) == 0 ? String(d: "%.0f", self) : String(format:"%.4f", self)
    }
}

expecting output to be 3.003 but getting like 3.004. i do want my last digit to be rounded to next digit.how to fix tho issue.any help will be appricated.thanks in advance

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
karthi
  • 11
  • 3
  • Does this answer your question? [How to truncate decimals to x places in Swift](https://stackoverflow.com/questions/35946499/how-to-truncate-decimals-to-x-places-in-swift) – rbaldwin May 20 '20 at 11:12

1 Answers1

0

If you use a NumberFormatter, you need to set the roundingMode to .floor to achieve truncating. Also, if you want to truncate, you probably want to set maximumFractionDigits instead of minimumFractionDigits.

extension Double {
    var string: String {
        let formatter = NumberFormatter()
        formatter.numberStyle = .decimal
        formatter.maximumFractionDigits = 4
        formatter.roundingMode = .floor
        return formatter.string(for: self) ?? description
    }
}

3.00035358.string // "3.0003"
Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116