Ruby中将浮点数转换为分数的代码是什么?
- 内容介绍
- 文章标签
- 相关推荐
本文共计338个文字,预计阅读时间需要2分钟。
python用户输入字符串user_input=67.99
将字符串转换为浮点数,然后乘以100,最后转换为整数converted_amount=int(float(user_input) * 100)
输出结果converted_amount
用户输入字符串’67 .99′.我需要最终将其转换为整数6799.换句话说:通过整数数据类型将通过字符串输入的货币金额转换为美分.
我注意到这种情况发生了:
('67.99'.to_f * 100).to_i #=> 6798
不期望的行为.我需要将它保存为6799,而不是6798.
问题是将此浮点数乘以100:
'67.99'.to_f * 100 #=> 6798.999999999999
问题:如何正确地将作为字符串输入的小数转换为整数?
示例输入和输出:
'67' #=> 6700 '67.' #=> 6700 '67.9' #=> 6790 '67.99' #=> 6799
IMO:这不是this question的重复,因为我知道浮动没有被破坏.
使用round:
('67.99'.to_f * 100).round #=> 6799
正如评论中所讨论的,有一种更好的方法可以处理这些字符串 – BigDecimal class:
(BigDecimal.new('67.99') * 100).round #=> 6799
这与大数字有关:
input = '1000000000000001' (input.to_f * 100).round #=> 100000000000000096 (BigDecimal.new(input) * 100).round #=> 100000000000000100
本文共计338个文字,预计阅读时间需要2分钟。
python用户输入字符串user_input=67.99
将字符串转换为浮点数,然后乘以100,最后转换为整数converted_amount=int(float(user_input) * 100)
输出结果converted_amount
用户输入字符串’67 .99′.我需要最终将其转换为整数6799.换句话说:通过整数数据类型将通过字符串输入的货币金额转换为美分.
我注意到这种情况发生了:
('67.99'.to_f * 100).to_i #=> 6798
不期望的行为.我需要将它保存为6799,而不是6798.
问题是将此浮点数乘以100:
'67.99'.to_f * 100 #=> 6798.999999999999
问题:如何正确地将作为字符串输入的小数转换为整数?
示例输入和输出:
'67' #=> 6700 '67.' #=> 6700 '67.9' #=> 6790 '67.99' #=> 6799
IMO:这不是this question的重复,因为我知道浮动没有被破坏.
使用round:
('67.99'.to_f * 100).round #=> 6799
正如评论中所讨论的,有一种更好的方法可以处理这些字符串 – BigDecimal class:
(BigDecimal.new('67.99') * 100).round #=> 6799
这与大数字有关:
input = '1000000000000001' (input.to_f * 100).round #=> 100000000000000096 (BigDecimal.new(input) * 100).round #=> 100000000000000100

