简体   繁体   中英

Correct way formatting digits into "X.XX" amount

I have a requirement to turn keyboard digits input into amount as cents, for example:

Typing 1 will output 0.01 Typing 10 will output 0.10 Typing 123 will output 1.23 Typing 12345 will output 123.45

My current solution involves multiplying by 0.01 and looking at the reminder:

// split into whole and reminder
   let mod = modf(doubleAmount * 0.01)

// define a rounding behavior
let behavior = NSDecimalNumberHandler(roundingMode: .plain,
                                      scale: Int16(places),
                                      raiseOnExactness: false,
                                      raiseOnOverflow: false,
                                      raiseOnUnderflow: false,
                                      raiseOnDivideByZero: true)

let whole = mod.0
let reminder = NSDecimalNumber(value: mod.1).rounding(accordingToBehavior: behavior)

// formatting...
let newnumber = NSNumber(value: whole + reminder.doubleValue)

This will work correct for most values but will break format when working with whole numbers like 10, 100, 1000 etc... The format will then be 0.1, 1.0, 10.0 while I need them to appear as 0.10, 1.00, 10.00 etc...

what is the best/correct way to achieve this?

The NumberFormatter type has a multiplier attribute that can be used for this scenario and then no further calculations will be needed

let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.minimumFractionDigits = 2
formatter.maximumFractionDigits = 2
formatter.multiplier = 0.01

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM