-2

I want floating numbers be limited for example to 8. When I run the below code it gives me 16 floating numbers. For example, x=4 and y=3, it gives 1.3333333333333333. How can I reduce the number of "3"s. NOTE: I DON'T WANT TO ROUND, JUST LIMIT "3"s.

x=int(input())
y=int(input())
print(x/y)
sassy_rog
  • 1,077
  • 12
  • 30
Yunis Rasulzade
  • 325
  • 3
  • 12
  • 3
    Possible duplicate of [Limiting floats to two decimal points](https://stackoverflow.com/questions/455612/limiting-floats-to-two-decimal-points) – sassy_rog Apr 28 '19 at 09:04

2 Answers2

2

You can easily do that if you

  • multiply the number by a power of 10
  • convert the number to int and
  • at last divide the number by the power of 10

So the code:

def limit_num(num, limit):
    num = num * 10**limit
    num = int(num)
    num /= 10**limit
    return num

number = 4/3 # 1.3333333333333333

number = limit_num(number, 5)

print(number) # 1.33333

Or in one line:

def limit_num(num, limit):
    return (int(num * 10**limit) / 10**limit)
Bence
  • 71
  • 1
  • 5
-1

round will not give you correct result if decimal digits are 999 types. You should convert float to string and try

def truncate_float_decimal(float_num, truncate_to_digits):
  base_length = len(float_num.split('.')[0])+1
  base_length += truncate_to_digits
  return  float((float_num[:base_length]))

truncated_float = truncate_float_decimal("14.999992223",7)
print (truncated_float)
mkrana
  • 422
  • 4
  • 10
  • `a` is undefined, and even with that error corrected, this produces [wrong results](https://ideone.com/0Kcd0w) for floats large enough or small enough that the string representation is in scientific notation – user2357112 Apr 28 '19 at 10:01