Programming

소수점 이하 숫자를 얻는 방법?

procodes 2020. 8. 25. 21:00
반응형

소수점 이하 숫자를 얻는 방법?


소수점 뒤의 숫자는 어떻게 구합니까?

예를 들어, 내가있는 5.55경우 어떻게 얻을 수 .55있습니까?


당신을위한 쉬운 접근 :

number_dec = str(number-int(number))[1:]

5.55 % 1

이것은 부동 소수점 반올림 문제에 도움이되지 않습니다. 즉, 다음을 얻을 수 있습니다.

0.550000000001

아니면 당신이 기대하는 0.55에서 약간 떨어져 있습니다.


modf 사용 :

>>> import math
>>> frac, whole = math.modf(2.5)
>>> frac
0.5
>>> whole
2.0

이건 어떤가요:

a = 1.3927278749291
b = a - int(a)

b
>> 0.39272787492910011

또는 numpy를 사용하여 :

import numpy
a = 1.3927278749291
b = a - numpy.fix(a)

decimal표준 라이브러리 모듈을 사용하면 원래 정밀도를 유지하고 부동 소수점 반올림 문제를 방지 할 수 있습니다.

>>> from decimal import Decimal
>>> Decimal('4.20') % 1
Decimal('0.20')

주석의 모든 메모 처럼 먼저 native float를 문자열 로 변환해야합니다 .


Modulo 시도 :

5.55%1 = 0.54999999999999982

import math
orig = 5.55
whole = math.floor(orig)    # whole = 5.0
frac = orig - whole         # frac = 0.55

받아 들여지는 대답과 비슷하게 문자열을 사용하는 더 쉬운 접근 방식은

if "." in str(number): # quick check if it is decimal
    number_dec = str(number).split(".")[1]

if 'e-' in str(number): # scientific notation
    number_dec = format(float(number_dec), '.%df'%(len(number_dec.split(".")[1].split("e-")[0])+int(number_dec.split('e-')[1])))

>>> n=5.55
>>> if "." in str(n):
...     print "."+str(n).split(".")[-1]
...
.55

floor를 사용하고 원래 숫자에서 결과를 뺍니다.

>> import math #gives you floor.
>> t = 5.55 #Give a variable 5.55
>> x = math.floor(t) #floor returns t rounded down to 5..
>> z = t - x #z = 5.55 - 5 = 0.55

이것은 내가 시도한 해결책입니다.

num = 45.7234
(whole, frac) = (int(num), int(str(num)[(len(str(int(num)))+1):]))

Float numbers are not stored in decimal (base10) format. Have a read through the python documentation on this to satisfy yourself why. Therefore, to get a base10 representation from a float is not advisable.

Now there are tools which allow storage of numeric data in decimal format. Below is an example using the Decimal library.

from decimal import *

x = Decimal('0.341343214124443151466')
str(x)[-2:] == '66'  # True

y = 0.341343214124443151466
str(y)[-2:] == '66'  # False

Example:

import math
x = 5.55
print((math.floor(x*100)%100))

This is will give you two numbers after the decimal point, 55 from that example. If you need one number you reduce by 10 the above calculations or increase depending on how many numbers you want after the decimal.


Sometimes trailing zeros matter

In [4]: def split_float(x):
   ...:     '''split float into parts before and after the decimal'''
   ...:     before, after = str(x).split('.')
   ...:     return int(before), (int(after)*10 if len(after)==1 else int(after))
   ...: 
   ...: 

In [5]: split_float(105.10)
Out[5]: (105, 10)

In [6]: split_float(105.01)
Out[6]: (105, 1)

In [7]: split_float(105.12)
Out[7]: (105, 12)

import math

x = 1245342664.6
print( (math.floor(x*1000)%1000) //100 )

It definitely worked


What about:

a = 1.234
b = a - int(a)
length = len(str(a))

round(b, length-2)

Output:
print(b)
0.23399999999999999
round(b, length-2)
0.234

Since the round is sent to a the length of the string of decimals ('0.234'), we can just minus 2 to not count the '0.', and figure out the desired number of decimal points. This should work most times, unless you have lots of decimal places and the rounding error when calculating b interferes with the second parameter of round.


You may want to try this:

your_num = 5.55
n = len(str(int(your_num)))
float('0' + str(your_num)[n:])

It will return 0.55.


number=5.55
decimal=(number-int(number))
decimal_1=round(decimal,2)
print(decimal)
print(decimal_1)

output: 0.55


Another crazy solution is (without converting in a string):

number = 123.456
temp = 1

while (number*temp)%10 != 0:
    temp = temp *10
    print temp
    print number

temp = temp /10
number = number*temp
number_final = number%temp
print number_final

참고URL : https://stackoverflow.com/questions/3886402/how-to-get-numbers-after-decimal-point

반응형