0

In py how to set float into 2 desimal by default

17th Sep 2019, 6:04 AM
Jason Lim
2 odpowiedzi
+ 5
float with only 2 decimal places: It depends what you really want to have. If you want to keep all the decimals of a float but for output / print you want to limit it to 2 decimals then you can do it like HonFu mentioned. If you really want to cut of all decimals except the first 2, you can use round(). round can be used in 2 different ways: f = 1.2345678 print(round(f, 2)) # output is 1.23, but f is still with all the decimal as it was created. f = 1.2345678 f = round(f, 2) print(f) # output is now 1.23, the rest of the decimals are truncated. Be aware that this can change and the number of decimals grow again if you start calculating with the truncated version. So 1.23 * 10 = 12.3 but adding f 10 times (f+f+...) it will result in 12.300000000000002
17th Sep 2019, 9:11 AM
Lothar
Lothar - avatar
+ 2
You can not change the float, you can only change the output with format strings, for example: x = 0.123456 print(f'{x:.2f}') If you have to do this for a lot of data, you can use loops or a function. https://realpython.com/JUMP_LINK__&&__python__&&__JUMP_LINK-f-strings/ EDIT: I totally forgot about the round function, can you believe it? 😱
17th Sep 2019, 6:27 AM
HonFu
HonFu - avatar