简体   繁体   English

Python - 将科学记数法字符串转换为保留小数位的浮点数

[英]Python - Convert scientific notation string to float retaining decimal places

I am using python to read some float values from a file.我正在使用 python 从文件中读取一些浮点值。 The values read are input to an 'Ada'(Programming Language) program.读取的值被输入到“Ada”(编程语言)程序。

The values being read are in different formats (scientific, decimal) and I would like to retain the format.正在读取的值采用不同的格式(科学、十进制),我想保留该格式。

Everything works well with simple float() operation except when converting '1.0e-5' to float.除了将 '1.0e-5' 转换为 float 时,一切都适用于简单的 float() 操作。

>>float('1.0e-5')
#returns 1e-5

1e-5 when used in Ada program gives 1e-5 在 Ada 程序中使用时给出

error:negative exponent not allowed for integer literal

1.0e-35 works with ada program. 1.0e-35 适用于 ada 程序。

I know if I use format I can get 1.0e-5我知道如果我使用格式我可以获得 1.0e-5

>>>"{:.1E}".format(float('1.0e-5'))
#returns '1.0E-5'

But this changes format for other read values also as my reading/manipulation function is common.但这也会更改其他读取值的格式,因为我的读取/操作功能很常见。

How should I approach this problem?我应该如何解决这个问题?

and if而如果

float('1.0')
#returns 1.0

why same behavior is not followed when converting a scientific notation string to float?为什么在将科学记数法字符串转换为浮点数时不遵循相同的行为?

(My reading/manipulation function is common. Using formatter string will change the formatting of other read values also) (我的读取/操作功能很常见。使用格式化字符串也会改变其他读取值的格式)

You could use a custom float to string conversion function which checks if the number will be accepted by Ada using a regular expression (which tests if there are only non-dots before the exponent character, and in which case only convert with format ):您可以使用自定义浮点到字符串转换函数,该函数使用正则表达式检查 Ada 是否接受该数字(测试指数字符之前是否只有非点,在这种情况下仅使用format转换):

import re

def ada_compliant_float_as_string(f):
    return "{:.1e}".format(f) if re.match("^-?[^\.]e",str(f)) else str(f)

for f in [-1e-5,1e-5,1.4e-5,-12e4,1,1.0]:
    print(ada_compliant_float_as_string(f))

prints:印刷:

-1.0e-05
1.0e-05
1.4e-05
-120000.0
1
1.0

only the first value is corrected, other values are just the string representation of a float, unchanged.只有第一个值被更正,其他值只是浮点数的字符串表示,不变。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM