PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, August 13, 2022

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

 August 13, 2022     decimal, integer, python     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing