search

Home  >  Q&A  >  body text

Fix currency format issue in PHP

<p><code>numfmt_format_currency(new NumberFormatter('en',2), 31.005, "USD")</code> This code outputs $31.00. But it should output $31.01. How to resolve this issue??? This code prints $31.00. But $31.01 should be output. how to solve this problem? ? </p><p>PHP ignores the conversion of 0.005 to 0.01 in price format. </p><p>I tried to fix Magento's currency formatting issue but found a problem with PHP</p><p><br /></p>
P粉322319601P粉322319601559 days ago742

reply all(1)I'll reply

  • P粉275883973

    P粉2758839732023-08-09 10:40:33

    31.005 is actually between the two numbers, see floating point precision at https://php.net/float.

    > ini_set('precision', 23)
    = "14"
    
    > 31.005
    = 31.00499999999999900524

    (In PHP and other languages, there is no number 31.005..)

    You need to provide numbers with sufficient precision, but with as little error as possible, to match your display requirements. This can be achieved by specifying the rounding mode, for example, if you want to round 31.005 to 31.01, you can choose to round up or round down.

    ##

    $formatter = new NumberFormatter('en', NumberFormatter::CURRENCY);
    
    $formatter->setAttribute(
        NumberFormatter::ROUNDING_MODE, 
        NumberFormatter::ROUND_HALFUP
    );
    
    
    echo $formatter->formatCurrency(31.005, 'USD'), "\n";
    # Output: .01
    

    This is what droopsnoot commented

    Number formatting default mode and creation

    As Olivier reminded in the comments, the default mode is semi-even rounding, also known as banker's rounding.

    At the same time, they pointed out that it would be "more formal" to use the class constant NumberFormatter::CURRENCY instead of using magic number 2

    $formatter = new NumberFormatter('en', 2);
    $formatter = new NumberFormatter('en', NumberFormatter::CURRENCY);
    

    This will allow your code to communicate better, otherwise the number 2 might be interpreted as the number of digits or precision, but that is not the case in this case. You can find all style constants in the PHP manual.

    Note: This is not just a PHP specific problem, you will encounter the same problem when you pass these numbers to Javascript and need to format them in Javascript.

    reply
    0
  • Cancelreply