Working with decimals

Joshua Landau joshua at landau.ws
Sat Aug 23 17:47:53 EDT 2014


On 23 August 2014 22:13, Seymore4Head <Seymore4Head at hotmail.invalid> wrote:
> def make_it_money(number):
>     import math
>     return '
> + str(format(math.floor(number * 100) / 100, ',.2f'))

So for one "import math" should never go inside a function; you should
hoist it to the top of the file with all the other imports.

You then have

    def make_it_money(number):
        return '$' + str(format(math.floor(number * 100) / 100, ',.2f'))

Consider the

    '$' + STUFF

This takes your formatted string (something like '12.43') and adds a
"$" to the front.

So then consider

    str(format(math.floor(number * 100) / 100, ',.2f'))

The first thing to note is that format is defined like so:

help(format)
#>>> Help on built-in function format in module builtins:
#>>>
#>>> format(...)
#>>>     format(value[, format_spec]) -> string
#>>>
#>>>     Returns value.__format__(format_spec)
#>>>     format_spec defaults to ""
#>>>

format returns a string, so the str call is unneeded.

You then consider that format takes two arguments:

    math.floor(number * 100) / 100

and

    ',.2f'

Looking at the (well hidden ;P) documentation
(https://docs.python.org/3/library/string.html#formatspec) you find:

"The ',' option signals the use of a comma for a thousands separator.
For a locale aware separator, use the 'n' integer presentation type
instead."

and

"The precision is a decimal number indicating how many digits should
be displayed after the decimal point for a floating point value
formatted with'f' and 'F', or before and after the decimal point for a
floating point value formatted with 'g' or 'G'."

So this says "two decimal places with a comma separator."

Then consider

    math.floor(number * 100) / 100

This takes a number, say 12345.6789, multiplies it by 100, to say
1234567.89, floors it, to say 1234567 and then divides by 100, to say,
12345.67.

In other words it floors to two decimal places. The one thing to note
is that binary floating point doesn't divide exactly by 100, so this
might not actually give a perfect answer. It'll probably be "good
enough" for your purposes though.



More information about the Python-list mailing list