How to get the first N digits of float number in Python

2 Answers

0 votes
import math 

def first_n_digits(number, n):
    return number // 10 ** (int(math.log(number, 10)) - n + 1)

f = 234.872
 
print(first_n_digits(f, 1))
print(first_n_digits(f, 2))
print(first_n_digits(f, 3))
print(first_n_digits(f, 4))
  
 
 
'''
run:
 
2.0
23.0
234.0
2348.0
 
'''

 



answered Aug 29, 2019 by avibootz
0 votes
import math 
from operator import *

def first_n_digits(number, n):
    return floordiv(number, 10 ** (int(math.log(number, 10)) - n + 1))


f = 234.872
 
print(first_n_digits(f, 1))
print(first_n_digits(f, 2))
print(first_n_digits(f, 3))
print(first_n_digits(f, 4))
  
 
 
'''
run:
 
2.0
23.0
234.0
2348.0
 
'''

 



answered Aug 29, 2019 by avibootz
...