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

Thursday, August 11, 2022

[FIXED] How to fix python float numbers exponential result

 August 11, 2022     c#, decimal, double, python     No comments   

Issue

I was playing with datatypes in python.

Every time, when I do

remaining_amount = .1 + .1 + .1 - .3

python gives an exponential result.

I try to do the same with c#

double remainingAmount = .1 + .1 + .1 - .3

It is also giving result in exponential form.

In both cases, the result is 5.55111512312578E-17

But in c#, when I change double to decimal, the result is 0.0

I am unable to understand why this is happening in both languages. And how can I fix this in python?


Solution

@Netwave is correct, as you wanted to fix this in python, the way would be decimal module:

>>> from decimal import Decimal
>>> Decimal('.1') + Decimal('.1') + Decimal('.1') - Decimal('.3')
Decimal('0.0')
>>> float(Decimal('.1') + Decimal('.1') + Decimal('.1') - Decimal('.3'))
0.0
>>> 


Answered By - U12-Forward
Answer Checked By - Marie Seifert (PHPFixing Admin)
  • 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