Trunc a number and get removed value. Or cast to int? - python

I try to get the removed part of the math.trunc function.
Or a function supports this request.
import math
number = 1.9
newnumber, removed = math.trunc(number)
I need the number = 1 and also the removed 0.9
So basicly i need the integer and the removed float.
Obove example will not work :/
Any suggestions ?

You need to keep a handle on the truncated number, and subtract it from the original number:
import math
number = 1.9
truncated = math.trunc(number)
print(truncated, number - truncated)

If you use modf you can flip the order of your variables and get the result you want.
import math
number = 1.9
removed, newnumber = math.modf(number)

For a starting point, use modulus 1 get the removed part.
def truncate(n):
return math.trunc(n), n % 1
Then you want to consider how negative numbers are handled. Do they return a positive ‘removed’ value?
This method won’t work for negative numbers, instead you can subtract the truncates number from the original:
t = math.trunc(n)
return t, n - t

Related

function round in python

i have some doubts in using round function correctly ,i want to know how i should use the round function correctly without any problem.
this is how how i coded in python code:
form1:
res = round(float(float(self.inst) - int(self.elt)),1)
also if put:
form2:
res1 = round(2*float(self.pro),1)
--->it doesn't give me any result .
in form1 ,when i put integer values it gives me result but when i put float values , nothing shown .help please i want those lignes of code work normal , with float and integer values.
in form2 nothing shown even i put integer or float values to see if the sentence work.
From round() documentation :
Return number rounded to ndigits precision after the decimal point. If
ndigits is omitted or is None, it returns the nearest integer to its
input.
Rounding an integer will always return the integer you passed to it, no matter what :
round(42, 50)
42
The second parameter is used to ask for a certain number of digit after the dot for floats.
round(1.2)
1
Cause 0 digit after dot is asked.
round(1.2, 1)
1.2
Cause 1 digit after dot is asked.
round(1.2,2)
1.2
2 digits are asked, but the floating number gave in parameter has only one digit.
In your case res1 and res are highly dependent of self.inst self.elt and self.pro so we cannot help you if you are not more specific. I suggest you write your code with one line by operation and check the results at each steps. I think your problem is not coming from the round() function, but the operations inside it.
By the way nobody will figure out what you try to achieve with those variable names.
You dont need the extra float conversion.
I am getting the below result -
a = '14.524'
b = 7.890
res = round((float(a) - int(b)), 1)
print(res)
7.5
res1 = round(2 * float(a), 1)
print(res1)
29
Check for errors in your terminal window.

How to convert a floating-point number to a fixed-width string?

I tried to find this question answered, but I haven't found anything related.
I have a variable that can be in a format like 50000.45 or in a format like 0.01.
I need to write this variable in a label that is 4 digits wide.
What is the best way to fit the label showing only the most significant digits?
To better explain, I would like to have for example:
for 50000.45: 50000
for 4786.847: 4786
for 354.5342: 354.5
for 11.43566: 11.43
and for 0.014556: 0.0145
Possibly without having to do:
if ... < variable < ...:
round(variable,xx)
for all cases.
In order to convert a number into a set number of digits, you can convert the number into only decimals (aka 0 <= n <= 1), then remove the last characters. You can do it like that:
from math import log10
number = 123.456789
n_digits = 4
log = int(log10(number) + 1)
number /= 10**log # convert the number into only decimals
number = int(number*10**n_digits)/10**n_digits # keep the n first digits
number *= 10**log # multiply the number back
Or a more compact form:
from math import log10
number = 123.456789
n_digits= 4
log = int(log10(number) + 1) - n_digits
number = int(number/10**log)*10**log
[Edit] You should use Python round() function in a simpler way:
number = round(number, n_digits-int(log10(number))-1)

Format number in python with leading zeros and fixed decimal places

I am trying to format a number into a string in python. The result I hope for is for 0.1423 to be converted to 000.14. I tried
num = 0.1423
print '%0.2f' %num
But this just results in the 0.14. I can't seem to get the leading zeros.
Cheers,
James
num = 0.1423
print '%06.2f' %num
The six indicates the total field width and includes the decimal point. The zero indicates include leading zeros, the 2 indicates the precision.
The field width has to be provided as well to get the required number of leading zeros:
print "%06.2f" % num
Output:
000.14
use str.format
print "{:06.2f}".format(num)

Python: Add character to string an amount of times depending on an int

Ok, I may have totally butchered the phrasing of this question since I can't quite word it but here's what I'm trying to do:
I have a CPU percentage displayed as characters in a string which show up on a display. If the cpu were at 52% I'd want the string to be CPU:[#####] 64% CPU:[######] but 77% CPU:[#######/] etc.
The only method I can thing off is having 20 if statements each with their own version of the string which shows dependant on the int percentage's value. I feel this would be a horrible way of doing it and wanted to know if there is a better way I can do this?
Assuming you want the number of hashes to be the “tens digit” of the CPU percentage, this simple function will do it:
def cpu_usage_str(cpu_percentage):
return 'CPU:[%s]' % ('#' * cpu_percentage / 10)
print cpu_usage_str(52)
print cpu_usage_str(64)
print cpu_usage_str(72)
(This assumes Python 2, with floor division. You’d need to tweak it slightly for Python 3.) We use the * operator to repeat the '#' string the appropriate number of times.
output:
CPU:[#####]
CPU:[######]
CPU:[#######]
Alternatively, if you’d like to round to the nearest ten (so 36% becomes CPU:[####], say), then this will do the trick:
def alt_cpu_usage_str(cpu_percentage):
return 'CPU:[%s]' % ('#' * int(round(cpu_percentage / 10.0)))
First we divide by 10.0 to get a float between 0.0 and 10.0. Then round takes us to the nearest whole number. This is represented by a float, so we convert it to an int and then repeat the string as before.
If we want a backslash to indicate whether we're under/over 5, then we need to consider cpu_percentage % 10 (the % is the modulo operator). Here's a function which does it:
def with_slashes_cpu_usage_str(cpu_percentage):
hashes_str = '#' * int(round(cpu_percentage / 10))
slash_str = '/' * (cpu_percentage % 10 >= 5)
return 'CPU:[{hash}{slash}]'.format(hash=hashes_str, slash=slash_str)
We construct the hash and slash strings separately. The bool cpu_percentage % 10 >= 5 is coerced to 0 or 1, which gives us the slash, or not, depending on whether or not we're in the upper half of that 10.
If you want [ ]5% not to print that trailing slash, then change to a strict inequality.
You can repeat a string using *, e.g. '#'*5 gives '#####'
print "CPU:[%s]"%('#'*(percentage/10))

Avoid rounding float in python

I have rather unusual request, but I hope someone might be able to help.
I am appending floats as values to numpy array.
I would like to make sure that float does not get rounded when its decimal part ends in 0.
For example:
I would like float 31.30 to stay 31.30 in the array, but what I am experiencing now is that it gets set to 31.3.
The reason why I want to make sure float does not change is that later on I am splitting it to two integers(31.30 to 31 and 30) and it is of critical importance for me that both integers have the 'complete' values.
Is there any way to get around this? I tried with making these floats strings, but my problem is that I need to compare the arrays with these floats and numpy.array_equal() does not seem to work for arrays of strings...
Any help will be greatly appreciated,
Best wishes
Since 31.3 and 31.30 are exactly the same number, there is no way to distinguish them. But I guess you don't need to anyway. This seems more like a formatting issue. If you always expect two digits after the dot:
from math import floor
x = 31.3
whole_part = int(floor(x))
two_after_dot = int(floor(x*100))-whole_part*100
print(whole_part, two_after_dot)
Output:
31 30
If this actually isn't the case and the number of digits after the dot should vary while also keeping varying numbers of trailing zeros, then you cannot use numeric types. Use strings from the very beginning instead.
When I ran into a similar problem because of converting millisecond references to microseconds, I had to convert to a string and loop over the string adding the needed 0's until the length of the string was correct. Then when the value was converted back to integer, the calculations worked.
The data will be passed to strptime as as string
vals = vals.split('.') # a fractional part of the seconds
nofrag, frag = vals
length = len(frag)
# This converts the fractional string to microseconds, given unknown precision
if length > 6:
frag = frag(0:5)
else:
while length < 6:
frag = frag + '0'
length += 1
# strptime requires even seconds with microseconds added later
nofrag_dt = DT.datetime.strptime(nofrag, '%Y%m%d %H%M%S')
dt = nofrag_dt.replace(microsecond=int(frag))
return dt

Categories