简体   繁体   English

从Swift(算法)中的十进制向上舍入

[英]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. 我正在开发销售应用程序,显示所选项目的总价格,并将根据总价格有3个总量建议。 These 3 total amounts are round up from the total price of selected items 这3个总金额是从所选项目的总价中四舍五入的

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 : 在我的国家有5种类型的钞票:

$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: 向上舍入到下一个5,10,50,...的倍数可以通过缩放来完成例如:

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". 这里nextUp用于将浮点数增加“一点点”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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