最接近五的圆形货币 [英] Round currency closest to five

查看:33
本文介绍了最接近五的圆形货币的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我想将我的值四舍五入到最接近的 5 美分:

I'd like to round my values to the closest of 5 cent for example:

5.31 -> 5.30
5.35 -> 5.35
5.33 -> 5.35
5.38 -> 5.40

目前我通过使用以下方法获取十进制值:

Currently I'm doing it by getting the decimal values using:

let numbers = 5.33
let decimal = (numbers - rint(numbers)) * 100
let rounded = rint(numbers) + (5 * round(decimal / 5)) / 100

// This results in 5.35

我想知道是否有一个步骤更少的更好的方法,因为有时 numbers - rint(numbers) 会给我一个奇怪的结果,比如:

I was wondering if there's a better method with fewer steps because sometimes numbers - rint(numbers) is giving me a weird result like:

let numbers = 12.12
let decimal = (numbers - rint(numbers)) * 100

// This results in 11.9999999999999

推荐答案

原来..真的很简单

let x: Float = 1.03 //or whatever value, you can also use the Double type
let y = round(x * 20) / 20

这篇关于最接近五的圆形货币的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆