简体   繁体   中英

Get round up double from decimal in Swift (Algorithm)

I am trying to achieve several number suggestion. But I couldn't find the algorithm on how to achieve it.

I am working on sales app that display the total price of selected items, and there will be 3 total amount suggestions based on the total price. These 3 total amounts are round up from the total price of selected items

So basically the user can choose either one of the suggested amount, solely for better user experience.

In my country there are 5 types of bank notes :

$1, $5, $10, $20, $50, $100

For example

Total Price: 307.40
First suggestion: 308.00
Second suggestion: 310.00
Third suggestion: 350.00

Total Price: 14.54
First suggestion: 15.00
Second suggestion: 20.00
Third suggestion: 50.00

Total Price: 131.82
First suggestion: 132.00
Second suggestion: 140.00
Third suggestion: 150.00

So basically, the suggested amount must be based on the bank notes. The examples above are just to describe the test case, it must not be as exactly same as above.

Can anyone guide me on how to achieve such function?

Thanks! Really appreciate any help given.

A floating point number is rounded up to the next integral value with

let price = 307.40;
let integralPrice = price.rounded(.up)    // 308.00

Rounding up to the next multiple of 5, 10, 50, ... can be done by scaling, for example:

let multipleOfTen   = (price / 10).rounded(.up) * 10    // 310
let multipleOfFifty = (price / 50).rounded(.up) * 50    // 350

And for multiples which are different from the given price and different from each other:

let price = 109.0;
let integralPrice = price.nextUp.rounded(.up)   // 110
let multipleOfTen   = (integralPrice.nextUp / 10).rounded(.up) * 10   // 120
let multipleOfFifty = (multipleOfTen.nextUp / 50).rounded(.up) * 50   // 150

Here nextUp is used to increment a floating point number by "a tiny bit".

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