phpformatprintf

sprintf()'s %g placeholder is truncating numbers with a comma as decimal separator


I have the following numbers: -4, -3.5, 0, 14.46

Which sprintf() format should I use?

Now I'm using %g, but this prints 14 from 14,46. Why is this happening?


Solution

  • As mentioned in: http://php.net/manual/en/function.sprintf.php

    %f - the argument is treated as a float, and presented as a floating-point number
    

    However, %g output is as following:

    echo sprintf('%s rating is %g', 'NAME', -4)."\r\n";
    echo sprintf('%s rating is %g', 'NAME', -3.5)."\r\n";
    echo sprintf('%s rating is %g', 'NAME', 0)."\r\n";
    echo sprintf('%s rating is %g', 'NAME', str_replace(',', '.', '1,74'))."\r\n";
    
    /* 
    NAME rating is -4
    NAME rating is -3.5
    NAME rating is 0
    NAME rating is 14.46
     */
    

    I think the problem is that $member->rating is float with decimal-point character comma.

    Applying str_replace(',', '.', $member->rating) should solve the issue.

    Try:

    echo sprintf('%s rating is %g', 'NAME', str_replace(',', '.', $member->rating))."\r\n";