2

I am receiving two kid of Doubles from JSON:

1.12 and 0.00007067999999

The second number switches automatically to scientific notation( 7.067e-05), so I'm using the function String(format:"%.8f", NUMBER) to make it 0.00007067, yes it works, but now my first number becomes 1.12000000. How to clean trailing numbers?

I've tried with Swift - Remove Trailing Zeros From Double , but the %g format changes second number to scientific notation again, so %g is not an option. Any suggestions?

picciano
  • 22,341
  • 9
  • 69
  • 82
Bogdan Bogdanov
  • 882
  • 11
  • 36
  • 79
  • What are you actually trying to achieve? If you want to store the actual numbers as doubles, you shouldn't care that the value is __displayed__ using the scientific notation. If you want to store the numbers as Strings, but make them have less fractional digits, you should use a `NumberFormatter`. – Dávid Pásztor Dec 23 '17 at 19:42

1 Answers1

3

You can use NumberFormater and set minimum and maximum fraction digits:

let double1 = 1.12
let double2 = 0.00007067999999

let numberFormatter = NumberFormatter()
numberFormatter.minimumFractionDigits = 2
numberFormatter.maximumFractionDigits = 8
numberFormatter.minimumIntegerDigits = 1
numberFormatter.string(for: double1) ?? ""   // "1.12"
numberFormatter.string(for: double2) ?? ""   // "0.00007068"

if you would like to round the fraction digits down you can set the formatter rounding mode option to .down:

numberFormatter.roundingMode = .down
numberFormatter.string(for: double2) ?? ""   // "0.00007067"
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571