在 Ruby 中将浮点数拆分为整数和小数 [英] Split float into integer and decimals in Ruby

查看:42
本文介绍了在 Ruby 中将浮点数拆分为整数和小数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个像 3.75 这样的浮点数,我怎样才能把它分成整数 3 和浮点数 0.75?

If I have a float like 3.75, how can I split it into the integer 3 and the float 0.75?

我是否必须将浮点数转换为字符串,然后用."分割字符串,然后再将部分转换为整数和浮点数,还是有更优雅或正确"的方法来做到这一点?

Do I have to convert the float into a string, and then split the string by ".", and then convert the parts into integers and floats again, or is there a more elegant or "right" way to do this?

推荐答案

如前所述,您可以使用 3.75.to_i 来获取整数.获取余数的另一种方法是使用 % 运算符,例如.3.75 % 1

As mentioned you can use 3.75.to_i to get the integer. An alternate way to get the remainder is using the % operator eg. 3.75 % 1

这篇关于在 Ruby 中将浮点数拆分为整数和小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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