Casebash - 5 months ago 17

Python Question

How do I round a decimal to a particular number of decimal places using the Python 3.0

`format`

Answer

Here's a typical, useful example...:

```
>>> n = 4
>>> p = math.pi
>>> '{0:.{1}f}'.format(p, n)
'3.1416'
```

the nested `{1}`

takes the second argument, the current value of n, and applies it as specified (here, to the "precision" part of the format -- number of digits after the decimal point), and the outer resulting `{0:.4f}`

then applies. Of course, you can hardcode the `4`

(or whatever number of digits) if you wish, but the key point is, you don't **have** to!

Even better...:

```
>>> '{number:.{digits}f}'.format(number=p, digits=n)
'3.1416'
```

...instead of the murky "argument numbers" such as 0 and 1 above, you can choose to use shiny-clear argument *names*, and pass the corresponding values as *keyword* (aka "*named*") arguments to `format`

-- that can be **so** much more readable, as you see!!!