RE: Floating numbers truncating to two digits without rounding

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



 Thanks for the info

-----Original Message-----
From: tedd [mailto:tedd@xxxxxxxxxxxx] 
Sent: Monday, January 09, 2006 3:26 PM
To: php-general@xxxxxxxxxxxxx; Mark Steudel
Subject: Re:  Floating numbers truncating to two digits without
rounding

>I am calculating things like tax and want to format them so they only 
>have 2 digits past the decimal point. I've been using sprintf but just 
>noticed that it tends to round up. I want the same functionlity without
rounding.

Mark:

Rounding?

You can try round(), such as:

<?php
echo round(3.4);         // 3
echo round(3.5);         // 4
echo round(3.6);         // 4
echo round(3.6, 0);      // 4
echo round(1.95583, 2);  // 1.96
echo round(1241757, -3); // 1242000
echo round(5.045, 2);    // 5.05
echo round(5.055, 2);    // 5.06
?>

But, as you can see, this rounds up (not the best).

You may want to consider that there is more than one way to round a number.
For example, there is no completely accurate solution for rounding any real
number. If you want absolute precision, then you must use absolute numbers
to whatever precision they are. However, this may not be obtainable because
of continuos numbers like pi. As such, you may be forced to round.

There are several different algorithms for rounding, such as truncation,
floor (rounding down), ceiling (round up), common, and statistical. None are
perfect, but some are more prone to errors than others. The least prone to
error is the statistical, please review:

"Statisticians method of rounding":

http://en.wikipedia.org/wiki/Rounding

And, if you ignore rounding, please review:

http://www.ima.umn.edu/~arnold/disasters/disasters.html

http://catless.ncl.ac.uk/php/risks/search.php?query=rounding

tedd

--
----------------------------------------------------------------------------
----
http://sperling.com/

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux