Thursday, December 7, 2023
HomeSoftware EngineeringTips on how to Format {Dollars} and Cents in Python

Tips on how to Format {Dollars} and Cents in Python

The problem

The corporate you’re employed for has simply been awarded a contract to construct a fee gateway. So as to assist transfer issues alongside, you might have volunteered to create a perform that can take a float and return the quantity formatting in {dollars} and cents.

39.99 turns into $39.99

The remainder of your crew will guarantee that the argument is sanitized earlier than being handed to your perform though you’ll need to account for including trailing zeros if they’re lacking (although you gained’t have to fret a couple of dangling interval).


3 must turn out to be $3.00

3.1 must turn out to be $3.10

The answer in Python code

Possibility 1:

def format_money(quantity):
    return "${:.2f}".format(quantity)

Possibility 2:

def format_money(quantity):
    return '$%0.2f' % quantity

Possibility 3:

format_money = '${:.2f}'.format

Take a look at circumstances to validate our answer

def tester328174(pattern):'Testing %s' % pattern)
  check.assert_equals(format_money(pattern), '$%0.2f' % pattern, "That is not formatted the best way we anticipated")
check.describe('Mounted exams')
for pattern in (39.99, 3, 3.10, 314.16):

check.describe('Random exams')
from random import random
for eiuqoiuwr838 in vary(1, 10):
  tester328174(int(random() * eiuqoiuwr838 * 100))
for eiuqoiuwr838 in vary(1, 19):
  tester328174(int(random() * eiuqoiuwr838 * 1000)/10.0)
for eiuqoiuwr838 in vary(1, 12):
  tester328174(int(random() * eiuqoiuwr838 * 10000)/100.0)


Please enter your comment!
Please enter your name here

Most Popular

Recent Comments