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

Wednesday, August 10, 2022

[FIXED] How to access the decimal numbers which are not stored in float value

 August 10, 2022     decimal, numbers, python     No comments   

Issue

If I want to access the 100th decimal of the number 1/919, is there a way to do so? I know that floating values are stored only upto certain decimals so I can access only the decimals which are stored but how to access the decimals which are not stored


Solution

Your intuition is correct. Python stores floats as 64-bit floating point values, which don't have the precision to go out to 100 decimals. You will have to use the decimal package and set the precision to what you need.

import decimal

# calculate up to 120 decimals
decimal.get_context().prec = 120

result = decimal.Decimal(1) / decimal.Decimal(919)
print(result)


# pull an arbitrary digit out of the string representation of the result
def get_decimal_digit(num, index):
    # find where the decimal points start
    point = str(num).rfind('.')
    return int(str(num)[index + point + 1])

# get the 100th decimal
print(get_decimal_digit(result, 100))


Answered By - dogman288
Answer Checked By - David Marino (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