python - String that represents float to fraction
问题描述
Im trying to handle a string like this:
s = '1/2.05'
When I try to parse it into a Fraction:
Fraction(s)
I am obtaining:
ValueError: ("Invalid literal for Fraction: u'1/2.05'", u'occurred at index 3')
I also tried:
Fraction(s.split('/')[0], s.split('/')[1])
But with error too:
TypeError: ('both arguments should be Rational instances', u'occurred at index 3')
How would the correct parsing be?
Thank you all in advance!
解决方案
问题在于分数和浮点数不会混合,因此您不能对直接在分数中隐藏浮点数的字符串进行类型转换。
但是不要为此使用 eval 。
尝试分别处理分子和分母。(您可以使用浮点数,但直接在字符串上调用 Fraction 会更精确,从而避免精度问题。)
from fractions import Fraction
s = '1/2.05'
numerator, denominator = s.split('/')
result = Fraction(numerator)/Fraction(denominator)
print(result)
推荐阅读
- python - 尝试导入版本的python中的相对导入错误
- c# - 选择元素不可见 - Mac - Safari 11.1 - Selenium - C#
- html - 如何使引导 4 d-flex 单元的高度相等?
语境
我正在使用
<table>
带有 bootstrap 4 的元素d-flex
来呈现表格。单元格 (<td>
) 在一行 ( ) 中有不同的内容<tr>
,不幸的是这会导致不同的单元格高度问题
- sql-server - VS2017 SQL Server 数据库项目跨数据库查询
- kubernetes - 限制 Kubernetes 服务帐户访问特定命名空间
- android - 从 adobe 18.3 版本应用程序共享 pdf 时,我无法在共享菜单列表中看到我的 Android 应用程序
- c# - 如何使用 angularjs 发布 blob 并在 C# 中接收 blob 到电子邮件
- python - 将值从一个类/函数传递到另一个类/函数
- powershell - 转储连接的驱动器序列号和用户
- android - Azure 通知中心仍然依赖 GCM,需要 6 个月才能关闭