如何在python中提取float的十进制值

时间:2022-02-15 17:18:12

I have a program that is a converter for times in minutes and seconds and returns a float value with a decimal, for example:

我有一个程序,它是一个转换器,用于分钟和秒的时间,并返回一个带小数的浮点值,例如:

6.57312

6.57312

I would like to extract the .57312 part in order to convert it to seconds.

我想提取.57312部分,以便将其转换为秒。

How can I get python to take only the value after the decimal point and put it into a variable that I can then use for the conversion?

我怎样才能让python只取小数点后的值并将其放入一个我可以用于转换的变量?

3 个解决方案

#1


11  

You can do just a simple operation

你可以做一个简单的操作

dec = 6.57312 % 1

#2


7  

math.modf does that. It also has the advantage that you get the whole part in the same operation.

math.modf就是这么做的。它还具有使整个部件处于同一操作中的优点。

import math
f,i = math.modf(6.57312)
# f == .57312, i==6.0

Example program:

示例程序:

import math
def dec_to_ms(value):
    frac,whole = math.modf(value)
    return "%d:%02d"%(whole, frac*60)

print dec_to_ms(6.57312)

#3


1  

You can do this also

你也可以这样做

num = 6.57312
dec = num-int(num)

#1


11  

You can do just a simple operation

你可以做一个简单的操作

dec = 6.57312 % 1

#2


7  

math.modf does that. It also has the advantage that you get the whole part in the same operation.

math.modf就是这么做的。它还具有使整个部件处于同一操作中的优点。

import math
f,i = math.modf(6.57312)
# f == .57312, i==6.0

Example program:

示例程序:

import math
def dec_to_ms(value):
    frac,whole = math.modf(value)
    return "%d:%02d"%(whole, frac*60)

print dec_to_ms(6.57312)

#3


1  

You can do this also

你也可以这样做

num = 6.57312
dec = num-int(num)