You are here: RE: [PHP] Floating numbers truncating to two digits without rounding « PHP « IT news, forums, messages
RE: [PHP] Floating numbers truncating to two digits without rounding

Posted by "Mark Steudel" on 01/10/06 17:45

Thanks for the info

-----Original Message-----
From: tedd [mailto:tedd@sperling.com]
Sent: Monday, January 09, 2006 3:26 PM
To: php-general@lists.php.net; Mark Steudel
Subject: Re: [PHP] 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/

 

Navigation:

[Reply to this message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация