Note that there are some explanatory texts on larger screens.

plurals
  1. POShowing decimal places (Python 2.7 and Decimal datatype)
    primarykey
    data
    text
    <p>I am trying to code a currency converter program, and instead of using floats am trying to code the program in Python 2.7.5 using the decimal data type.</p> <p>The program works and displays a result, but when using the getcontext().prec = 2 this is limiting the amount of numbers shown to 2, not the number of decimal places</p> <p>code shown below:</p> <pre><code>#setup the decimal data type (including number of decimal places) import decimal decimal.getcontext().prec = 2 #get the current value and type from the user currencyAmount = decimal.Decimal(raw_input('please enter the amount: ')) currencyType = int(raw_input('please enter the type (1 = pound, 2 = euro, 3 = dollar, 4 = yen): ')) #set the exchange rates (based on sterling) euro = decimal.Decimal('1.5') dollar = decimal.Decimal('2.7') yen = decimal.Decimal('30.8') #convert the currency into pound sterling if (currencyType == 2): currencyAmount = currencyAmount / euro elif (currencyType == 3): currencyAmount = currencyAmount / dollar elif (currencyType == 4): currencyAmount = currencyAmount / yen #ask the user what currency they want it converted into currencyConvert = int(raw_input('please enter the currency you would like to convert to (1 = pound, 2 = euro, 3 = dollar, 4 = yen): ')) #convert the currency into the new format (pound already done in previous steps) if (currencyConvert == 2): currencyAmount = currencyAmount * euro elif (currencyConvert == 3): currencyAmount = currencyAmount * dollar elif (currencyConvert == 4): currencyAmount = currencyAmount * yen #display the result to the user print 'the result of the currency conversion was ', currencyAmount </code></pre> <p>UPDATE:</p> <p>tried the suggested code, but came up against the following error when running the program:</p> <pre><code>Traceback (most recent call last): File "C:\Users\nhornus154\Desktop\currencyConverter.py", line 34, in &lt;module&gt; print 'the result of the currency conversion was ', currencyAmount.quantize(Decimal('0.00')) NameError: name 'Decimal' is not defined </code></pre> <p>also tried to change to decimal.Decimal, but responded that the arguments were not correct for quantize</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload