Method for formatting a decimal number in Python using the given maximum number of digits and decimal...

Why are electrically insulating heatsinks so rare? Is it just cost?

Linear Path Optimization with Two Dependent Variables

Modeling an IP Address

Is it unprofessional to ask if a job posting on GlassDoor is real?

Approximately how much travel time was saved by the opening of the Suez Canal in 1869?

Arrow those variables!

Horror movie about a virus at the prom; beginning and end are stylized as a cartoon

What defenses are there against being summoned by the Gate spell?

Why is consensus so controversial in Britain?

DC-DC converter from low voltage at high current, to high voltage at low current

Maximum likelihood parameters deviate from posterior distributions

Paid for article while in US on F1 visa?

Why can't we play rap on piano?

A newer friend of my brother's gave him load of baseball cards that are supposedly extremely valuable. Is this a scam?

How is the claim "I am in New York only if I am in America" the same as "If I am in New York, then I am in America?

Was any UN Security Council vote triple-vetoed?

How bulky would the original autograph of the Torah been?

Replacing matching entries in one column of a file by another column from a different file

if condition in the past

Filter any system log file by date or date range

Why is 150k or 200k jobs considered good when there's 300k+ births a month?

Convert two switches to a dual stack, and add outlet - possible here?

Accidentally leaked the solution to an assignment, what to do now? (I'm the prof)

Watching something be written to a file live with tail



Method for formatting a decimal number in Python using the given maximum number of digits and decimal places


Finding the lowest decimal number for a given integerJava helper function to round a number to the specified number of decimal placesGet an integer as input and display Pi rounded to that amount of decimal placesNext bigger number with the same digitsCount digits in a given number using recursionFind the maximum line length in a given TSV columString formatting for uint64_t that represents a fixed-point decimalFind maximum number in a nested array using recursionFormatting the opposite of some numbers, with decimal alignmentPython Find the N adjacent digits in the 1000-digit number that have the greatest product






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ margin-bottom:0;
}







7












$begingroup$


The question itself should be fairly self-explanatory. My method takes in value, max_digits, and decimal_places, and returns a formatted decimal number string. The code:



from decimal import Decimal, ROUND_DOWN

def format_to_decimal_string(value, max_digits, decimal_places):
"""Formats a decimal number to the given number of decimal places.

Notes:
- If the decimal number is equal to zero, the absolute of the decimal
number is formatted and returned to remove the minus sign. See the
first doctest for an example.
- If the number of digits in the rounded up decimal number exceeds the
`max_digits`, the method tries to return the rounded down version. See
the second doctest for an example.

Doctests:
>>> format_to_decimal_string('-0.000', 4, 2)
'0.00'
>>> format_to_decimal_string('99.999999', 4, 2)
'99.99'
>>> format_to_decimal_string('99.999999', 5, 2)
'100.00'
>>> format_to_decimal_string('420.2108', 5, 0)
'420'
>>> format_to_decimal_string('foo', 4, 2)
Traceback (most recent call last):
...
TypeError: The value 'foo' is not a valid decimal number.
>>> format_to_decimal_string('120.411', 4, 2)
Traceback (most recent call last):
...
ValueError: After formatting, the number of digits in the value
'120.41' is 5, which exceeds the maximum number of digits of 4.
"""
try:
decimal_number = Decimal(str(value))
except:
raise TypeError(
'The value '{}' is not a valid decimal number.'.format(value)
)

if decimal_number == 0:
return str(abs(decimal_number).quantize(
Decimal(10) ** -decimal_places)
)

rounded_up = decimal_number.quantize(Decimal(10) ** -decimal_places)
if not len(rounded_up.as_tuple().digits) > max_digits:
return str(rounded_up)

rounded_down = decimal_number.quantize(
Decimal(10) ** -decimal_places,
rounding=ROUND_DOWN
)
rounded_down_digits_length = len(rounded_down.as_tuple().digits)
if not rounded_down_digits_length > max_digits:
return str(rounded_down)
else:
raise ValueError(
'After formatting, the number of digits in the value '{}' is '
'{}, which exceeds the maximum number of digits of {}.'.format(
rounded_down, rounded_down_digits_length, max_digits
)
)


Please assume that max_digits, and decimal_places will always be positive integers, and max_digits is greater than decimal_places, because these are coming from my database, so no validation is required for these arguments.



The comments should also be self explanatory. We only want to round up if the rounding up does not exceed the given maximum number of digits. Would really appreciate a review of this method.










share|improve this question











$endgroup$



















    7












    $begingroup$


    The question itself should be fairly self-explanatory. My method takes in value, max_digits, and decimal_places, and returns a formatted decimal number string. The code:



    from decimal import Decimal, ROUND_DOWN

    def format_to_decimal_string(value, max_digits, decimal_places):
    """Formats a decimal number to the given number of decimal places.

    Notes:
    - If the decimal number is equal to zero, the absolute of the decimal
    number is formatted and returned to remove the minus sign. See the
    first doctest for an example.
    - If the number of digits in the rounded up decimal number exceeds the
    `max_digits`, the method tries to return the rounded down version. See
    the second doctest for an example.

    Doctests:
    >>> format_to_decimal_string('-0.000', 4, 2)
    '0.00'
    >>> format_to_decimal_string('99.999999', 4, 2)
    '99.99'
    >>> format_to_decimal_string('99.999999', 5, 2)
    '100.00'
    >>> format_to_decimal_string('420.2108', 5, 0)
    '420'
    >>> format_to_decimal_string('foo', 4, 2)
    Traceback (most recent call last):
    ...
    TypeError: The value 'foo' is not a valid decimal number.
    >>> format_to_decimal_string('120.411', 4, 2)
    Traceback (most recent call last):
    ...
    ValueError: After formatting, the number of digits in the value
    '120.41' is 5, which exceeds the maximum number of digits of 4.
    """
    try:
    decimal_number = Decimal(str(value))
    except:
    raise TypeError(
    'The value '{}' is not a valid decimal number.'.format(value)
    )

    if decimal_number == 0:
    return str(abs(decimal_number).quantize(
    Decimal(10) ** -decimal_places)
    )

    rounded_up = decimal_number.quantize(Decimal(10) ** -decimal_places)
    if not len(rounded_up.as_tuple().digits) > max_digits:
    return str(rounded_up)

    rounded_down = decimal_number.quantize(
    Decimal(10) ** -decimal_places,
    rounding=ROUND_DOWN
    )
    rounded_down_digits_length = len(rounded_down.as_tuple().digits)
    if not rounded_down_digits_length > max_digits:
    return str(rounded_down)
    else:
    raise ValueError(
    'After formatting, the number of digits in the value '{}' is '
    '{}, which exceeds the maximum number of digits of {}.'.format(
    rounded_down, rounded_down_digits_length, max_digits
    )
    )


    Please assume that max_digits, and decimal_places will always be positive integers, and max_digits is greater than decimal_places, because these are coming from my database, so no validation is required for these arguments.



    The comments should also be self explanatory. We only want to round up if the rounding up does not exceed the given maximum number of digits. Would really appreciate a review of this method.










    share|improve this question











    $endgroup$















      7












      7








      7





      $begingroup$


      The question itself should be fairly self-explanatory. My method takes in value, max_digits, and decimal_places, and returns a formatted decimal number string. The code:



      from decimal import Decimal, ROUND_DOWN

      def format_to_decimal_string(value, max_digits, decimal_places):
      """Formats a decimal number to the given number of decimal places.

      Notes:
      - If the decimal number is equal to zero, the absolute of the decimal
      number is formatted and returned to remove the minus sign. See the
      first doctest for an example.
      - If the number of digits in the rounded up decimal number exceeds the
      `max_digits`, the method tries to return the rounded down version. See
      the second doctest for an example.

      Doctests:
      >>> format_to_decimal_string('-0.000', 4, 2)
      '0.00'
      >>> format_to_decimal_string('99.999999', 4, 2)
      '99.99'
      >>> format_to_decimal_string('99.999999', 5, 2)
      '100.00'
      >>> format_to_decimal_string('420.2108', 5, 0)
      '420'
      >>> format_to_decimal_string('foo', 4, 2)
      Traceback (most recent call last):
      ...
      TypeError: The value 'foo' is not a valid decimal number.
      >>> format_to_decimal_string('120.411', 4, 2)
      Traceback (most recent call last):
      ...
      ValueError: After formatting, the number of digits in the value
      '120.41' is 5, which exceeds the maximum number of digits of 4.
      """
      try:
      decimal_number = Decimal(str(value))
      except:
      raise TypeError(
      'The value '{}' is not a valid decimal number.'.format(value)
      )

      if decimal_number == 0:
      return str(abs(decimal_number).quantize(
      Decimal(10) ** -decimal_places)
      )

      rounded_up = decimal_number.quantize(Decimal(10) ** -decimal_places)
      if not len(rounded_up.as_tuple().digits) > max_digits:
      return str(rounded_up)

      rounded_down = decimal_number.quantize(
      Decimal(10) ** -decimal_places,
      rounding=ROUND_DOWN
      )
      rounded_down_digits_length = len(rounded_down.as_tuple().digits)
      if not rounded_down_digits_length > max_digits:
      return str(rounded_down)
      else:
      raise ValueError(
      'After formatting, the number of digits in the value '{}' is '
      '{}, which exceeds the maximum number of digits of {}.'.format(
      rounded_down, rounded_down_digits_length, max_digits
      )
      )


      Please assume that max_digits, and decimal_places will always be positive integers, and max_digits is greater than decimal_places, because these are coming from my database, so no validation is required for these arguments.



      The comments should also be self explanatory. We only want to round up if the rounding up does not exceed the given maximum number of digits. Would really appreciate a review of this method.










      share|improve this question











      $endgroup$




      The question itself should be fairly self-explanatory. My method takes in value, max_digits, and decimal_places, and returns a formatted decimal number string. The code:



      from decimal import Decimal, ROUND_DOWN

      def format_to_decimal_string(value, max_digits, decimal_places):
      """Formats a decimal number to the given number of decimal places.

      Notes:
      - If the decimal number is equal to zero, the absolute of the decimal
      number is formatted and returned to remove the minus sign. See the
      first doctest for an example.
      - If the number of digits in the rounded up decimal number exceeds the
      `max_digits`, the method tries to return the rounded down version. See
      the second doctest for an example.

      Doctests:
      >>> format_to_decimal_string('-0.000', 4, 2)
      '0.00'
      >>> format_to_decimal_string('99.999999', 4, 2)
      '99.99'
      >>> format_to_decimal_string('99.999999', 5, 2)
      '100.00'
      >>> format_to_decimal_string('420.2108', 5, 0)
      '420'
      >>> format_to_decimal_string('foo', 4, 2)
      Traceback (most recent call last):
      ...
      TypeError: The value 'foo' is not a valid decimal number.
      >>> format_to_decimal_string('120.411', 4, 2)
      Traceback (most recent call last):
      ...
      ValueError: After formatting, the number of digits in the value
      '120.41' is 5, which exceeds the maximum number of digits of 4.
      """
      try:
      decimal_number = Decimal(str(value))
      except:
      raise TypeError(
      'The value '{}' is not a valid decimal number.'.format(value)
      )

      if decimal_number == 0:
      return str(abs(decimal_number).quantize(
      Decimal(10) ** -decimal_places)
      )

      rounded_up = decimal_number.quantize(Decimal(10) ** -decimal_places)
      if not len(rounded_up.as_tuple().digits) > max_digits:
      return str(rounded_up)

      rounded_down = decimal_number.quantize(
      Decimal(10) ** -decimal_places,
      rounding=ROUND_DOWN
      )
      rounded_down_digits_length = len(rounded_down.as_tuple().digits)
      if not rounded_down_digits_length > max_digits:
      return str(rounded_down)
      else:
      raise ValueError(
      'After formatting, the number of digits in the value '{}' is '
      '{}, which exceeds the maximum number of digits of {}.'.format(
      rounded_down, rounded_down_digits_length, max_digits
      )
      )


      Please assume that max_digits, and decimal_places will always be positive integers, and max_digits is greater than decimal_places, because these are coming from my database, so no validation is required for these arguments.



      The comments should also be self explanatory. We only want to round up if the rounding up does not exceed the given maximum number of digits. Would really appreciate a review of this method.







      python python-3.x formatting fixed-point






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 29 at 20:27









      200_success

      131k17157422




      131k17157422










      asked Mar 29 at 16:21









      darkhorsedarkhorse

      1804




      1804






















          2 Answers
          2






          active

          oldest

          votes


















          4












          $begingroup$

          Your code looks quite good to me. Good structure, consistent naming, appropriate documentation.



          There are just some small ideas I would like to offer to you. Since your question is specifically tagged for Python 3, you might make use of the new f-string synthax instead of format. So your error messages would become something like



          raise TypeError(
          f"The value '{value}' is not a valid decimal number."
          )


          which I think looks even nicer. I also replaced the outer ' with " so one does not have to escape the inner ' with backslashes.



          The last error message could use the same tricks and could also utilize implicit line continuation in function parenthesis instead of manual line continuation triggered by . This would ultimately lead to the following snippet:



          raise ValueError(
          f"After formatting, the number of digits in the value '{rounded_down}' "
          f"is {rounded_down_digits_length}, which exceeds the maximum number of "
          f"digits of {max_digits}."
          )


          I was thinking about to address the idea of adding doctests to your code, but you have added this feature in an edit that took place while is was writing this up. So consider this to be done.






          share|improve this answer









          $endgroup$





















            1












            $begingroup$

            Some other minor issues:



            Invert your logic



            if not len(rounded_up.as_tuple().digits) > max_digits:


            should be



            if len(rounded_up.as_tuple().digits) <= max_digits:


            Lose the redundant else



            This:



            if not rounded_down_digits_length > max_digits:
            return str(rounded_down)
            else:
            raise ...


            can just be



            if rounded_down_digits_length <= max_digits:
            return str(rounded_down)
            raise ...





            share|improve this answer









            $endgroup$













            • $begingroup$
              Can you tell my why the inversion of logic is necessary? Is this mentioned somewhere in some best practices doc or something?
              $endgroup$
              – darkhorse
              Mar 31 at 14:27










            • $begingroup$
              It's not necessary, but it is more legible. In the modified syntax, you don't need to write a not. I can't really find a reference for this, but I stand by it.
              $endgroup$
              – Reinderien
              Mar 31 at 15:34












            Your Answer





            StackExchange.ifUsing("editor", function () {
            return StackExchange.using("mathjaxEditing", function () {
            StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
            StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
            });
            });
            }, "mathjax-editing");

            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "196"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: false,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: null,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f216484%2fmethod-for-formatting-a-decimal-number-in-python-using-the-given-maximum-number%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            4












            $begingroup$

            Your code looks quite good to me. Good structure, consistent naming, appropriate documentation.



            There are just some small ideas I would like to offer to you. Since your question is specifically tagged for Python 3, you might make use of the new f-string synthax instead of format. So your error messages would become something like



            raise TypeError(
            f"The value '{value}' is not a valid decimal number."
            )


            which I think looks even nicer. I also replaced the outer ' with " so one does not have to escape the inner ' with backslashes.



            The last error message could use the same tricks and could also utilize implicit line continuation in function parenthesis instead of manual line continuation triggered by . This would ultimately lead to the following snippet:



            raise ValueError(
            f"After formatting, the number of digits in the value '{rounded_down}' "
            f"is {rounded_down_digits_length}, which exceeds the maximum number of "
            f"digits of {max_digits}."
            )


            I was thinking about to address the idea of adding doctests to your code, but you have added this feature in an edit that took place while is was writing this up. So consider this to be done.






            share|improve this answer









            $endgroup$


















              4












              $begingroup$

              Your code looks quite good to me. Good structure, consistent naming, appropriate documentation.



              There are just some small ideas I would like to offer to you. Since your question is specifically tagged for Python 3, you might make use of the new f-string synthax instead of format. So your error messages would become something like



              raise TypeError(
              f"The value '{value}' is not a valid decimal number."
              )


              which I think looks even nicer. I also replaced the outer ' with " so one does not have to escape the inner ' with backslashes.



              The last error message could use the same tricks and could also utilize implicit line continuation in function parenthesis instead of manual line continuation triggered by . This would ultimately lead to the following snippet:



              raise ValueError(
              f"After formatting, the number of digits in the value '{rounded_down}' "
              f"is {rounded_down_digits_length}, which exceeds the maximum number of "
              f"digits of {max_digits}."
              )


              I was thinking about to address the idea of adding doctests to your code, but you have added this feature in an edit that took place while is was writing this up. So consider this to be done.






              share|improve this answer









              $endgroup$
















                4












                4








                4





                $begingroup$

                Your code looks quite good to me. Good structure, consistent naming, appropriate documentation.



                There are just some small ideas I would like to offer to you. Since your question is specifically tagged for Python 3, you might make use of the new f-string synthax instead of format. So your error messages would become something like



                raise TypeError(
                f"The value '{value}' is not a valid decimal number."
                )


                which I think looks even nicer. I also replaced the outer ' with " so one does not have to escape the inner ' with backslashes.



                The last error message could use the same tricks and could also utilize implicit line continuation in function parenthesis instead of manual line continuation triggered by . This would ultimately lead to the following snippet:



                raise ValueError(
                f"After formatting, the number of digits in the value '{rounded_down}' "
                f"is {rounded_down_digits_length}, which exceeds the maximum number of "
                f"digits of {max_digits}."
                )


                I was thinking about to address the idea of adding doctests to your code, but you have added this feature in an edit that took place while is was writing this up. So consider this to be done.






                share|improve this answer









                $endgroup$



                Your code looks quite good to me. Good structure, consistent naming, appropriate documentation.



                There are just some small ideas I would like to offer to you. Since your question is specifically tagged for Python 3, you might make use of the new f-string synthax instead of format. So your error messages would become something like



                raise TypeError(
                f"The value '{value}' is not a valid decimal number."
                )


                which I think looks even nicer. I also replaced the outer ' with " so one does not have to escape the inner ' with backslashes.



                The last error message could use the same tricks and could also utilize implicit line continuation in function parenthesis instead of manual line continuation triggered by . This would ultimately lead to the following snippet:



                raise ValueError(
                f"After formatting, the number of digits in the value '{rounded_down}' "
                f"is {rounded_down_digits_length}, which exceeds the maximum number of "
                f"digits of {max_digits}."
                )


                I was thinking about to address the idea of adding doctests to your code, but you have added this feature in an edit that took place while is was writing this up. So consider this to be done.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Mar 29 at 20:28









                AlexAlex

                1,325418




                1,325418

























                    1












                    $begingroup$

                    Some other minor issues:



                    Invert your logic



                    if not len(rounded_up.as_tuple().digits) > max_digits:


                    should be



                    if len(rounded_up.as_tuple().digits) <= max_digits:


                    Lose the redundant else



                    This:



                    if not rounded_down_digits_length > max_digits:
                    return str(rounded_down)
                    else:
                    raise ...


                    can just be



                    if rounded_down_digits_length <= max_digits:
                    return str(rounded_down)
                    raise ...





                    share|improve this answer









                    $endgroup$













                    • $begingroup$
                      Can you tell my why the inversion of logic is necessary? Is this mentioned somewhere in some best practices doc or something?
                      $endgroup$
                      – darkhorse
                      Mar 31 at 14:27










                    • $begingroup$
                      It's not necessary, but it is more legible. In the modified syntax, you don't need to write a not. I can't really find a reference for this, but I stand by it.
                      $endgroup$
                      – Reinderien
                      Mar 31 at 15:34
















                    1












                    $begingroup$

                    Some other minor issues:



                    Invert your logic



                    if not len(rounded_up.as_tuple().digits) > max_digits:


                    should be



                    if len(rounded_up.as_tuple().digits) <= max_digits:


                    Lose the redundant else



                    This:



                    if not rounded_down_digits_length > max_digits:
                    return str(rounded_down)
                    else:
                    raise ...


                    can just be



                    if rounded_down_digits_length <= max_digits:
                    return str(rounded_down)
                    raise ...





                    share|improve this answer









                    $endgroup$













                    • $begingroup$
                      Can you tell my why the inversion of logic is necessary? Is this mentioned somewhere in some best practices doc or something?
                      $endgroup$
                      – darkhorse
                      Mar 31 at 14:27










                    • $begingroup$
                      It's not necessary, but it is more legible. In the modified syntax, you don't need to write a not. I can't really find a reference for this, but I stand by it.
                      $endgroup$
                      – Reinderien
                      Mar 31 at 15:34














                    1












                    1








                    1





                    $begingroup$

                    Some other minor issues:



                    Invert your logic



                    if not len(rounded_up.as_tuple().digits) > max_digits:


                    should be



                    if len(rounded_up.as_tuple().digits) <= max_digits:


                    Lose the redundant else



                    This:



                    if not rounded_down_digits_length > max_digits:
                    return str(rounded_down)
                    else:
                    raise ...


                    can just be



                    if rounded_down_digits_length <= max_digits:
                    return str(rounded_down)
                    raise ...





                    share|improve this answer









                    $endgroup$



                    Some other minor issues:



                    Invert your logic



                    if not len(rounded_up.as_tuple().digits) > max_digits:


                    should be



                    if len(rounded_up.as_tuple().digits) <= max_digits:


                    Lose the redundant else



                    This:



                    if not rounded_down_digits_length > max_digits:
                    return str(rounded_down)
                    else:
                    raise ...


                    can just be



                    if rounded_down_digits_length <= max_digits:
                    return str(rounded_down)
                    raise ...






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Mar 30 at 20:57









                    ReinderienReinderien

                    5,250926




                    5,250926












                    • $begingroup$
                      Can you tell my why the inversion of logic is necessary? Is this mentioned somewhere in some best practices doc or something?
                      $endgroup$
                      – darkhorse
                      Mar 31 at 14:27










                    • $begingroup$
                      It's not necessary, but it is more legible. In the modified syntax, you don't need to write a not. I can't really find a reference for this, but I stand by it.
                      $endgroup$
                      – Reinderien
                      Mar 31 at 15:34


















                    • $begingroup$
                      Can you tell my why the inversion of logic is necessary? Is this mentioned somewhere in some best practices doc or something?
                      $endgroup$
                      – darkhorse
                      Mar 31 at 14:27










                    • $begingroup$
                      It's not necessary, but it is more legible. In the modified syntax, you don't need to write a not. I can't really find a reference for this, but I stand by it.
                      $endgroup$
                      – Reinderien
                      Mar 31 at 15:34
















                    $begingroup$
                    Can you tell my why the inversion of logic is necessary? Is this mentioned somewhere in some best practices doc or something?
                    $endgroup$
                    – darkhorse
                    Mar 31 at 14:27




                    $begingroup$
                    Can you tell my why the inversion of logic is necessary? Is this mentioned somewhere in some best practices doc or something?
                    $endgroup$
                    – darkhorse
                    Mar 31 at 14:27












                    $begingroup$
                    It's not necessary, but it is more legible. In the modified syntax, you don't need to write a not. I can't really find a reference for this, but I stand by it.
                    $endgroup$
                    – Reinderien
                    Mar 31 at 15:34




                    $begingroup$
                    It's not necessary, but it is more legible. In the modified syntax, you don't need to write a not. I can't really find a reference for this, but I stand by it.
                    $endgroup$
                    – Reinderien
                    Mar 31 at 15:34


















                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Code Review Stack Exchange!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    Use MathJax to format equations. MathJax reference.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f216484%2fmethod-for-formatting-a-decimal-number-in-python-using-the-given-maximum-number%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    is 'sed' thread safeWhat should someone know about using Python scripts in the shell?Nexenta bash script uses...

                    How do i solve the “ No module named 'mlxtend' ” issue on Jupyter?

                    Pilgersdorf Inhaltsverzeichnis Geografie | Geschichte | Bevölkerungsentwicklung | Politik | Kultur...