Saturday, August 13, 2022

[FIXED] How to prevent converting decimal to int while doing math in Python?

Issue

How do I prevent converting a Decimal to an int while doing math (executing functions like // or *) in Python?

To get the input as a decimal number, I am using Decimal from the decimal module.

When I do

from decimal import Decimal

foo = Decimal(input())

And input 3.8, it outputs 3.8, which is right. However, when I add a mathematical function, like

print (foo // 2)

to my code, it outputs 1, whereas it's supposed to output 1.4.

Is there any way to prevent this from happening, as the program that I am making depends on decimals.


Solution

Don’t use //, just use /. // is floor division. This divides and returns the integer value of the quotient. It dumps the digits after the decimal.



Answered By - Niels Henkens
Answer Checked By - Clifford M. (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.