Evan Gilbert Long
Evan Gilbert Long

Reputation: 59

How to extract the decimal value of float in python

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

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

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?

Upvotes: 4

Views: 2365

Answers (3)

itzMEonTV
itzMEonTV

Reputation: 20369

You can do this also

num = 6.57312
dec = num - int(num)

Upvotes: 3

Robᵩ
Robᵩ

Reputation: 168866

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

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)

Upvotes: 7

rafaelc
rafaelc

Reputation: 59284

You can do just a simple operation

dec = 6.57312 % 1

Upvotes: 12

Related Questions