Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove leading zero from double calculation?

Tags:

swift

Consider the following, how do I remove the leading zero, and retain 3 decimals places? savePercentageDecimals returns 0.923, I would like just .923

    //Figure out Save Percentage
    let savePercentage = 12.0 / (1.0 + 12.0)
    let savePercentageDecimals = String(format: "%.3f",savePercentage)

Thanks in advance!

like image 259
Paul S. Avatar asked Jan 24 '26 22:01

Paul S.


1 Answers

NumberFormatter is the class you want to use when displaying numbers as string. In your case, this will work :

let formatter = NumberFormatter()
formatter.minimumIntegerDigits = 0
formatter.minimumFractionDigits = 3
formatter.maximumFractionDigits = 3

let savePercentage = 12.0 / (1.0 + 12.0)
let savePercentageDecimals = formatter.string(from: NSNumber(value: savePercentage)) // .923

By using minimumIntegerDigits above, it doesn't remove leading significant numbers (>= 1):

let moreThan100Percent = (12.0 / (1.0 + 12.0)) + 1.0
let formattedWithDecimals = formatter.string(from: NSNumber(value: moreThan100Percent)) // 1.923
like image 106
tgyhlsb Avatar answered Jan 26 '26 17:01

tgyhlsb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!