How to create output that will return numver with two decimals, despite those two decimals being 00?
Such as 12.00
I tried using round (points,2) that didn’t work
I tried adding “.ToString (“0.00”)” from Stack Overflow. I don’t really understand the principle and besides, it doesn’t work…
Could someone tell me what I’m doing wrong?
I’ve just tried it and it works amazing. I am new to coding so hope you don’t mind me asking for a bit of an explanation on this bit (or if you can point me in the direction of some resources explaining it):
if len(result.split(".")[1]) < 2: # If the length of result ....?... after the decimal point ...?... is less than 2
final += "0" #Add another zero to the string
I am curious about the [1] and where exactly did we split the number?
Ooo wait I think I understand something
We didn’t split the number, we split the string at the place of dot (not decimal point) and told the computer to look at the rest of the string after the “.”
So the result.split(‘.’) thing basically split the result by the dot, so it should be something like [decimal(number), decimal points]
The [1] thing specifies your target to the decimal point thing but not the number before the dot
Adding on to what TaokyleYT said, split() converts a string into a list, dividing it at every occurrence of whatever string we fed it as a parameter (in this case a period/decimal point). So, since there is one decimal point in your float turned string, there are two list items. Python starts counting at 0 so the decimal digits are item 1 and the numbers before the decimal would be item 0.
In python, the correct way to specify 2 decimal places is with number formatting.
Use an f-string (formatted string literal) to put values in a string, with curly brackets ({})
x = 12.5
f"{x}% value" == "12.5% value"
Then, specify formatting options within the curly brackets after a colon (:). The format specifier .2f means to show a precision of 2 decimal places. (will round more precise values using the rounding half to even method)
percent = 60.0
result = f"a {percent:.2f}% increase"
assert result == "a 60.00% increase"