Python将字符串数转换为小数位

时间:2017-05-21 11:46:38

标签: python python-2.7

我使用下面的代码将字节转换为KB-MB-GB-TB

a = 2048 * 1073741824
def bytes_2_human_readable(number_of_bytes):
    if number_of_bytes < 0:
        raise ValueError("!!! numberOfBytes can't be smaller than 0 !!!")

    step_to_greater_unit = 1024.

    number_of_bytes = float(number_of_bytes)
    unit = 'bytes'

    if (number_of_bytes / step_to_greater_unit) >= 1:
        number_of_bytes /= step_to_greater_unit
        unit = 'KB'

    if (number_of_bytes / step_to_greater_unit) >= 1:
        number_of_bytes /= step_to_greater_unit
        unit = 'MB'

    if (number_of_bytes / step_to_greater_unit) >= 1:
        number_of_bytes /= step_to_greater_unit
        unit = 'GB'

    if (number_of_bytes / step_to_greater_unit) >= 1:
        number_of_bytes /= step_to_greater_unit
        unit = 'TB'
    print number_of_bytes
    precision = 1
    number_of_bytes = round(number_of_bytes, precision)

    b = str(number_of_bytes) + '' + unit
print b
bytes_2_human_readable(a)

我得到2TB的输出就像是2.0TB

且1.5TB仅为1.5TB

现在2TB的另一侧或命令输出我得到2TB 对于1.5TB,我得到1.50TB

现在我需要比较这些值。

a = 1.0TB
b = 1TB
c = 1.5TB
d = 1.50TB

以上所有变量均为字符串格式

现在我需要匹配(注意下面的代码不起作用,只是示例,以显示我期待的内容)

if a == b:
   print "Should match even if a = 1.0TB and b 1TB"
else:
   print "B size is different value if value is more or less"
if c == d:
   print "Should match even if c = 1.5TB and b 1.50TB"
else:
   print "d size is different value if value is more less"

请帮助最好将1.0TB转换为1TB和1.5TB转换为1.50TB

1 个答案:

答案 0 :(得分:0)

从您的评论中我假设您的问题只是如何删除值上的尾随0而不是如何将TB与GB等进行比较。

好吧,谢天谢地,python非常适合处理字符串。

def remove_trailing_zeros(string):
    suffixes = ['KB', 'MB', 'GB', 'TB']

    for s in suffixes:
        string = string.replace('.0'+s, s)
        string = string.replace('0'+s, s)

    return string