[英]Raising an error if a dict value has more than specified number of digits
I'm trying to raise an error if a value in a dict has greater than eg 6 digits (would be useful to test for a particular number of decimal places too).如果 dict 中的值大于例如 6 位(对于测试特定的小数位数也很有用),我试图引发错误。
eg for the dict below (and say number digits = 6)例如对于下面的字典(并说数字= 6)
example_dict = {'dict_id': 12345,
'key1': 10501.04999999999999999262}
for key, value in tariff_detail.items():
if value == type(float) and (test for number of digits):
raise ValueError("DictID: {}, Key Missing: {}".format(example_dict['dict_id'],key))
(Note if I stick the above example in ipython and do example_dict.values() it pops out [10501.05] - Is there in built rounding or is this just for display?) (请注意,如果我在 ipython 中粘贴上面的示例并执行 example_dict.values() 它会弹出 [10501.05] - 是否存在内置舍入还是仅用于显示?)
What's the best way to test for the number of digits and raise an error on fail?测试位数并在失败时引发错误的最佳方法是什么?
一种简单的方法是将值转换为字符串,然后计算其长度:
if len(str(value)) > 6 :
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.