LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   [php]sprintf issue that I don't understand (https://www.linuxquestions.org/questions/programming-9/%5Bphp%5Dsprintf-issue-that-i-dont-understand-697472/)

Wim Sturkenboom 01-15-2009 06:33 AM

[php]sprintf issue that I don't understand
 
The following code calculates a percentage for an uptime
Code:

    $uptime=100 * ($total['runtime'] - $total['downtime']) / $total['runtime'];
    debug_print($uptime);
    $uptime=sprintf("%2.2f", $uptime);
    echo $uptime;

The output for a certain calculation is 99.996136186824 (for the debug_print) and 100.00 for the echo. I expected the latter to output 99.99.

Is my understanding of the sprintf precision specifier wrong? I thought it would simply chop the last digits off, but it seems to round first.

PHP version 4.3.10

jlinkels 01-15-2009 07:38 PM

It is the same in C.

Maybe not what you expected, but it is also scientifically correct. If you specify the precision of a number in 2 decimals, the number has an uncertainty of 0.005.

Which means:

100.00 can be: 99.995 < value < 100.005 (which 99.9961.... is) This is scientifically correct.

If your output would have been 99.99, the original number could have been: 99.985 < value < 99.995 which is not correct.

So the precision specifier does exactly what the name says: it specifies the precision, not the number of decimal places. Yes, many text writers cut some corners and say it is the number of decimal places. If that were true, 99.9961... would be displayed as 99.99. But is does not correctly reflect the value that you measured.

(On a side note: it is therefore nonsense for a digital multimeter to display 1.534 as battery voltage if the meter has 1% accuracy)

If your display is 100.00, you can be sure the availability was > 99.995%. If you want to show that it was less than 100%, you have to use a higher precision.

jlinkels

graemef 01-15-2009 08:09 PM

If you always want to floor it then try...
PHP Code:

echo floor($uptime*100)/100


Wim Sturkenboom 01-15-2009 10:57 PM

Thanks

I know it's mathematically correct, but did not expect it. As a programmer I want it mathematically correct, as a user I don't expect to see an uptime of 100% if there was the smallest amount of downtime. I will talk to the customer (again).

And I indeed used a floor to solve the issue.

Thanks again


All times are GMT -5. The time now is 04:34 AM.