Home > Mobile >  How can I add a $ sign to Total Gas Cost and Cost Per Mile output?
How can I add a $ sign to Total Gas Cost and Cost Per Mile output?

Time:06-04

How can I add a $ in the front of the calculates value. e.g., $ 64.6

# Calculate and display total gas cost`enter code here`
total_gas_cost = round(gallons_used * cost_per_gallon, 2)
print("Total Gas Cost:\t", total_gas_cost)

# Calculate and display cost per mile
cost_per_mile = round(cost_per_gallon / miles_per_gallon)
print("Cost Per Mile:\t", cost_per_mile)

CodePudding user response:

Try this:

print("Total Gas Cost:\t$ ", total_gas_cost)

Or, better:

print(f"Total Gas Cost:\t$ {total_gas_cost:.2f}")

This is an f-string. The .2f after the variable name says, "show 2 decimal places". It's often better to do this than to round the variable itself, which might lead to imprecision.

CodePudding user response:

You can use locale module:

import locale

locale.setlocale( locale.LC_ALL, 'en_US.UTF-8' )

print("Total Gas Cost:", locale.currency(total_gas_cost))
  • Related