Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,894 questions

51,825 answers

573 users

How to implement a function that truncate float in Python

2 Answers

0 votes
def truncate(f, n):
    i = int(f * (10**n)) / (10**n)
    
    return float(i)
    
print(truncate(4478.123789, 4))
print(truncate(127.50, 4))
print(truncate(127.51, 4))


    
    

'''
run:

4478.1237
127.5
127.51

'''

 



answered Apr 26, 2021 by avibootz
0 votes
def truncate(f, n):
    s = str(f)
    for i in range(len(s)):
        if s[i] == '.':
            try:
                return float(s[:i + n + 1])
            except:
                return float(s)      
    return float(s)
    
print(truncate(4478.123789, 4))
print(truncate(127.50, 4))
print(truncate(127.51, 4))


    
    

'''
run:

4478.1237
127.5
127.51

'''

 



answered Apr 26, 2021 by avibootz

Related questions

1 answer 112 views
112 views asked Apr 26, 2021 by avibootz
1 answer 164 views
1 answer 82 views
2 answers 176 views
...