-7

What I want.

A: $1.10 = $1.1

B: $0.10101010101 = $0.101010

What I've tried

Solution one - String(format: "%.6f", price)

This will do the following:

A: $1.100000 B: $0.1010101

So B is gets the correct outcome but A gets more decimals.

Solution two - numberFormatter.numberStyle = .decimal This gives the following outcome

A: $1.1 B: $0.1

So here A is correct but B gets rounded up.

user3116871
  • 313
  • 2
  • 5
  • 18
  • 1
    Please, show us the exact code and your input data. Did you try to set number of decimal digits for `NumberFormatter`? – Sulthan Dec 10 '21 at 13:01
  • 1
    after Solution one.. https://newbedev.com/swift-remove-trailing-zeros-from-double – Ben Rockey Dec 10 '21 at 13:02
  • 3
    The question says "Double" but it seems like you're actually asking about a `String`? –  Dec 10 '21 at 13:34

2 Answers2

0

This code will work for removing trailing zeros

let distanceFloat1: Float = 1.10 let distanceFloat2: Float = 0.10101010101

print("Value \(distanceFloat1.clean)")

print("Value \(distanceFloat2.clean)") 

extension Float {
    var clean: String {
       return self.truncatingRemainder(dividingBy: 1) == 0 ? String(format: "%.0f", self) : String(self)
    }
}

Output

Value 1.1
Value 1.101010

if you want to remove trailing zeros, also want to remove decimals after x place use

Swift - Remove Trailing Zeros From Double

Noman Umar
  • 369
  • 1
  • 7
  • I like this, its very clean – user3116871 Dec 10 '21 at 13:56
  • 3
    I do not understand the logic. This will print 1.1 as "1.1", and 1.0 as "1.000000". Also the output of the second number is "0.1010101", and not "0.101010" as you claim. – Martin R Dec 10 '21 at 14:11
  • 1
    Your last edit didn't fix the problem for 0.10101010101 and now this is an exact duplicate of the answer posted by OP – Joakim Danielson Dec 10 '21 at 14:29
  • Your latest version is an exact copy of (e.g.) the code in https://stackoverflow.com/a/35946921/1187415. – Martin R Dec 10 '21 at 14:42
  • 2
    This is just fundamentally flawed. I'm not sure why everyone has the constant drive towards `String(format:)`, when `NumberFormatter` already exists, and is *actually correct*. – Alexander Dec 10 '21 at 19:12
-1

I removed the trailing zeros using Ben's answer.

var stringWithoutZeroFraction: String {
    return truncatingRemainder(dividingBy: 1) == 0 ? String(format: "%.0f", self) : String(self)
}
user3116871
  • 313
  • 2
  • 5
  • 18