I remember that book... you're making a custom template filter right? You need to convert the value being passed in to locale.currency from a string to an int/decimal/float.

Best practice to avoid rounding errors with currency is to use the decimal package. Import the decimal package and pass your value through the Decimal function to fix the issue.

    from decimal import Decimal
    value = Decimal(value)

So your code should look like this:

    from django import template

    import locale
    from decimal import Decimal

    register = template.Library()    
    
    @register.filter(name='currency')    
    def currency(value):    
        try:    
            locale.setlocale(locale.LC_ALL,'en_US.UTF-8')    
        except:    
            locale.setlocale(locale.LC_ALL,'')    
        value = Decimal(value)    
        loc = locale.localeconv()    
        return locale.currency(value, loc['currency_symbol'], grouping=True)
Answer from Higgs Bogson on Stack Overflow
🌐
Python Examples
pythonexamples.org › python-absolute-value-abs
abs() - Python Examples
If we provide an argument of any non-numeric type like string, abs() function raises TypeError. x = 'hello' absVal = abs(x) print(f'Absolute value of {x} is {absVal}.') Traceback (most recent call last): File "example1.py", line 2, in <module> absVal = abs(x) TypeError: bad operand type for ...
Discussions

[Python 3.4] Making a simple program to print the absolute value of integer but coming up with an error
https://docs.python.org/3.4/library/functions.html#abs abs(x) Return the absolute value of a number. The argument may be an integer or a floating point number. https://docs.python.org/3.4/library/functions.html#input input([prompt]) The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. https://docs.python.org/3.4/library/functions.html#int int(x=0) Return an integer object constructed from a number or string x, or return 0 if no arguments are given. More on reddit.com
🌐 r/learnprogramming
8
3
June 6, 2014
TypeError: bad operand type for abs(): 'str'
sample.zip I'm running NIPT samples then suddenly I found this error occurred in some samples [INFO - 2021-04-29 10:19:51]: Starting CNA prediction [INFO - 2021-04-29 10:19:51]: Importing data ... More on github.com
🌐 github.com
2
August 11, 2020
python - Variable comes up as a string; TypeError: bad operand type for abs(): 'str' - Stack Overflow
When trying to run this code, it seems to insist that variable x is a string, even after double checking that it is an integer and converting it to one. import time x = 0 while True: print(&qu... More on stackoverflow.com
🌐 stackoverflow.com
Checking the type of data
if type(d) == float or int: is the culprit. you need if type(d) == float or type(d) == int: More on reddit.com
🌐 r/learnprogramming
9
3
September 18, 2023
🌐
Pytut
pytut.com › abs
Python abs() Function - PyTut
The argument can't be a str, tuple, list, set, or dict. These raise TypeError. >>> abs('-3.5') Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: bad operand type for abs(): 'str' >>> abs((1, -1)) Traceback (most recent call last): File "<stdin>", line 1, in <module> ...
🌐
Scaler
scaler.com › home › topics › python abs() function
Python abs() Function - Scaler topics
December 4, 2023 - As we can see, we passed the 'str' data type to abs() function, and the result is an error - bad operand type.
🌐
GitHub
github.com › CenterForMedicalGeneticsGhent › WisecondorX › issues › 79
TypeError: bad operand type for abs(): 'str' · Issue #79 · CenterForMedicalGeneticsGhent/WisecondorX
August 11, 2020 - TypeError: bad operand type for abs(): 'str'#79 · Copy link · KhanhLPBao · opened · on Apr 29, 2021 · Issue body actions · sample.zip I'm running NIPT samples then suddenly I found this error occurred in some samples · [INFO - 2021-04-29 10:19:51]: Starting CNA prediction [INFO - 2021-04-29 10:19:51]: Importing data ...
Published   Apr 29, 2021
🌐
Django
code.djangoproject.com › ticket › 11411
#11411 (DecimalField and NaN) – Django
Exception Type: TypeError Exception Value: bad operand type for abs(): 'str' Exception Location: /var/lib/python-support/python2.6/django/forms/fields.py in clean, line 254
Find elsewhere
🌐
Reddit
reddit.com › r/learnprogramming › checking the type of data
r/learnprogramming on Reddit: Checking the type of data
September 18, 2023 -

Hey guys. I'm currently learning Python and yesterday I ran into my first hurdle. This is the practice problem:

Create a function, called distance_from_zero(), that returns the absolute value of a provided single argument and prints a statement "Not possible" if the argument provided is not a number. To solve the task, use the type() function in the body of distance_from_zero(). Call the function with the values of -10 and "cat" to verify it works correctly.

Here is the code that I created:

def distance_from_zero(d):
if type(d) == float or int:
    return abs(d)
else:
    print("Not possible")

Whenever I input an integer or float to test the code, it works. However, when I test for strings, it does not print "Not possible" but instead throws an error. This is the error that it produces:

TypeError                                 Traceback (most recent call last)

Cell In[6], line 1 ----> 1 distance_from_zero("asd")

Cell In[2], line 3, in distance_from_zero(d) 1 def distance_from_zero(d): 2 if type(d) == float or int: ----> 3 return abs(d) 4 else: 5 print("Not possible")

TypeError: bad operand type for abs(): 'str'

In my understanding, the "if type(d) == float or int:" should produce a false boolean response which should cause it to print "Not possible", but instead, I'm getting an error. Hopefully someone can point out my mistake or where I understood incorrectly? Thank you in advance!

🌐
iO Flood
ioflood.com › blog › python-absolute-value
Python Absolute Value | abs() Function and Alternatives
February 6, 2024 - string = 'Hello, Python!' try: absolute_value = abs(string) except TypeError: print('TypeError: bad operand type for abs(): str') # Output: # TypeError: bad operand type for abs(): str · In this code block, we tried to find the absolute value of a string, which resulted in a TypeError.
🌐
GitHub
github.com › BelowSubway › SillytavernExpressionCreator › issues › 1
bad operand type for abs(): 'str' · Issue #1 · BelowSubway/SillytavernExpressionCreator
August 22, 2024 - bad operand type for abs(): 'str'#1 · Copy link · byslexic · opened · on Nov 3, 2024 · Issue body actions ·
Author   byslexic
🌐
Checkio
py.checkio.org › forum › post › 13102 › bad-operand-type-for-abs-how-do-i-solve-this
'Bad operand type for abs', how do i solve this
'Bad operand type for abs', how do i solve this ?: def checkio(numbersarray: tuple) -> list: result = sorted([numbersarray], key=lambda x:abs(x)) return result · task.absolute-sorting · Created: March 3, 2019, 9:51 p.m. Updated: March 3, 2019, 11:02 p.m. 0 · 6 · matdibobe ·
Top answer
1 of 1
1

I don't recommend you use apply here

Use GroupBy.idxmax + DataFrame.replace

max_df = df.abs().groupby(np.arange(len(df)) // n).idxmax().replace(df)
print(max_df)

Output

           A          B          C          D
0  95.483784  72.261024  90.289008 -99.557204
1  92.303663 -92.933734  98.741863 -73.221129
2 -94.858459  91.925163  90.394739  94.129047
3  85.727608  96.168424  69.747412  74.943672

print(df)
 # df = pd.read_clipboard() # read

            A          B          C          D
0  -49.710250 -44.714960  90.289008  78.021054
1   15.779849  72.261024 -80.564941 -99.557204
2  -25.535893  44.418568  -3.654055  -4.656012
3   -1.792691  52.828214 -24.383645  54.337480
4   95.483784 -33.604944  60.210426 -68.157859
5   85.614669 -88.756766  14.634241 -73.221129
6   -1.461207  41.078068  98.741863   0.152652
7   92.303663 -77.230608  63.205845 -45.439176
8   36.255957 -92.933734  -8.668916  24.251590
9   15.387012 -17.044411 -84.098159  53.797730
10 -15.277586  91.925163  90.394739  94.129047
11 -94.858459  19.069534  62.672051  10.852176
12 -48.550836  59.084142 -22.185758 -58.797477
13 -16.430060 -26.718411 -23.169127  90.198812
14  14.495206  14.054623 -59.593696  35.043442
15  21.148221  16.673029  42.788121 -23.932640
16  74.617433 -53.114081  69.747412  74.943672
17  85.727608  96.168424  41.474511   7.672894
18  -9.282754  -0.151546  -8.765613 -26.973899
19 -39.272002  85.819052  21.355006  67.018427

The problem is that Groupby.apply apply the function to each daframe, then max receives a dataframearg... We could check it with:

def absmax(x):
    print('This is a DataFrame arg: \n', x)
    return x.apply(lambda y: max(y, key=abs))

df_max = df.groupby(np.arange(len(df))//n).apply(absmax)

This is a DataFrame arg: 
            A          B          C          D
0  23.080753  89.918599 -62.273324   0.674636
1 -61.096176  68.840583  20.359616 -82.110220
2 -86.942716  97.269852  57.320944  84.340152
3  36.632979  53.376849  95.817563  39.398515
4 -36.960907 -12.796490 -79.833804  32.708664
This is a DataFrame arg: 
            A          B          C          D
5  24.360600 -49.486819 -65.995965 -93.884078
6 -46.623600 -57.999896 -86.946372  -0.250644
7 -35.103092  61.971385  86.165203 -32.619381
8  50.155064 -38.999355  98.856747 -56.195841
9 -92.646512  94.217864 -86.628196 -55.859978
This is a DataFrame arg: 
             A          B          C          D
10 -55.846413  34.281246 -90.523268  71.148029
11  22.753896 -33.659637  74.225409  24.498337
12 -52.384172  16.169118 -10.788839 -99.874961
13  49.235215 -74.372901  11.509361 -43.676953
14  67.255287 -84.477123  12.725054 -85.892184
This is a DataFrame arg: 
             A          B          C          D
15  72.522972 -13.079824  48.973703 -87.913843
16 -64.110924 -81.324560   7.067080  97.073997
17  87.319482  76.021534  80.780322 -90.320084
18 -84.848110  70.732111  34.160013  99.269365
19 -17.924337  12.191496  46.020178  30.532568
🌐
TutorialKart
tutorialkart.com › python › pandas › pandas-dataframe-abs
Absolute Function to each Element of DataFrame in Pandas
July 12, 2021 - Example.py · </> Copy · import ... print(result) Output · TypeError: bad operand type for abs(): 'str' Absolute method works only with numeric elements....
🌐
GitHub
github.com › dirkjanm › ldapdomaindump › issues › 51
TypeError: bad operand type for abs(): 'str' · Issue #51 · dirkjanm/ldapdomaindump
April 25, 2022 - TypeError: bad operand type for abs(): 'str'#51 · Copy link · deni · opened · on Jan 11, 2023 · Issue body actions · I am experiencing a problem that seems similar to #27. Please see below: (venv) deni@NCCBook-Pro ldapdomaindump-0.9.4 % python ldapdomaindump.py 10.129.139.146 [*] Connecting as anonymous user, dumping will probably fail.
Published   Jan 11, 2023
🌐
Invent with Python
inventwithpython.com › appendixd.html
IYOCGwP, Appendix D
This error occurs when the value of an argument you pass to a function or method is of the wrong data type. In the above example, the abs() function takes an integer or floating point number. Passing a string for the argument results in an error.
🌐
Codecademy
codecademy.com › forum_questions › 50b9bcd5e26c29acd0000e98
I can't see ANYTHING wrong with this code, why do I keep getting the same error? | Codecademy
def distance_from_zero(x): a = type(x) b = abs(x) if a == int or float: print b else: print “This isn’t an integer or a float!”
🌐
CopyProgramming
copyprogramming.com › howto › bad-operand-type-for-abs-str
Python: Invalid data type for the absolute value of a string
June 15, 2023 - TypeError: 'str' is an invalid operand type for abs() function when a variable is passed as a string, Invalid operand type for abs() function in Django: 'str', Encountering an error 'bad operand type for abs(): 'str'' when applying a function to pandas columns, Adding string text after utilizing ...
🌐
Dynamo
forum.dynamobim.com › revit
Python absolute value - Revit - Dynamo
June 6, 2019 - hello, I am trying to get rid off the absolute value, but I don’t understand why I am getting error xVal = IN[0] xout= for x in xVal: b = abs(x): if b<150: xout.append("Less than 150 Pipe is " + str(b)) else: x…
🌐
Studytonight
studytonight.com › pandas › pandas-dataframe-abs-method
Pandas DataFrame abs() Method - Studytonight
April 12, 2023 - We will get TypeError if try to get the absolute value of string because abs() methods allow only numeric values.