0

I have a model representing billionaires and certain statistics about them. One of the fields is ytd_change, a float representing the amount of net worth the subject gained since the previous year, in millions of US dollars. (This metric was in the original corpus, not calculated.) Negative numbers indicate losses in net worth.

For positive dollar amounts, it's simple enough. But net worth losses come out odd:

Example:

<li>{{ billionaire.name }}: ${{ billionaire.ytd_change }}M</li>

For Larry Page and Carlos Slim respectively, this evaluates to:

  • Larry Page: $4720.0M
  • Carlos Slim: $-75.3M

Is there an elegant way to get the negative sign in the proper place (i.e. "-$75.3M") with the built-in filters? It doesn't seem right to handle this in the view. Should I add representational methods to the model? Or is a custom filter the best answer?

K1nesthesia
  • 147
  • 1
  • 3
  • 11
  • Maybe if the number is less than 0 then take the absolute value of the number then format the string how you want it? Check out this link to see more. https://stackoverflow.com/questions/26839925/convert-negative-number-to-positive-number-in-django-template/26841129 . I also agree with @iklinac – MsonC Dec 13 '20 at 03:33
  • 1
    You could write yourself a simple template tag https://docs.djangoproject.com/en/3.1/howto/custom-template-tags/#writing-custom-template-tags – iklinac Dec 13 '20 at 03:34
  • @Chris DTL is Django Template Language. I thought that was common parlance? – K1nesthesia Dec 13 '20 at 03:36
  • 1
    @MasonCurtis I thought of that, but felt there must be a more elegant way. Seems like a custom tag is my best option, judging from the reaction. – K1nesthesia Dec 13 '20 at 03:39

1 Answers1

2

In my project, I used two ways to achieve this:

  1. one way is using stringformat and slice
-${{x|stringformat:".1f"|slice"1:"}}

stringformat:".1f" is to convert float number to string: -75.3 ---> '-75.3'. The number 1 is to keep one digit after the decimal point.

slice"1:" is to remove -. The result is '-75.3'----> '75.3'

  1. another one is using mathfilters' abs
{% load mathfilters %}

-${{x|abs}}

Of cause, you need to plug these into {% if x < 0 %} {% endif %} statement.

At the end, it is not as elegant as custom template tag, but if one does not want to write own custom template tag, the above solutions should help.

ha-neul
  • 3,058
  • 9
  • 24