Number & Float in Python

whitehousechef·2024년 8월 6일

math.ceil

both ceil and floor rounds down and up to nearest integer.

int(10e9) vs 10**9

omg i didnt know but e itself is 10!! so the left is actually doing 10*10^9 so 10^10!! So when we are doing % mod, we need to declare as 10**9!!!!

Truncate off 2 dp and more (V. IMPT)

If we wanna cut off from 2dp and just get up to 1dp and attach a 0 at the end, it is trickier than just rounding up to 2 dp blindly. For this, we have to use a little trick of multiplying our float by 10, then math.floor on that, which will give us a whole number, then divide it by 10 (/). This essentially is the same float but we effectively removed 2dp and onwards.

hola_down = 202.3975
print(math.floor(hola_down*10)/10)

Then, if we want to attach a 0 at the 2nd dp, we use f-string with :.2f, which rounds UP to 2dp.

ans = math.floor(hola_down*10)/10
print(f"{ans:.2f}")

0개의 댓글