Bezug:
PHP (
Zend)
Details:
Sometimes you need to truncate a number (float or double) to a specified count of decimals. But whatever function you use e.g. (s)printf, number_format, round (floor, ceil) it just does not truncate your number but rounds it for God's sake.
To output a simply truncated but not rounded number you want the following truncate function. It uses some simple math. It adds a small offset to your number and then uses the rounding fetish of sprintf to fit your needs. Here we go:
<?php
/**
* sprintf() does normal rounding.
* To achieve a truncation an appropriate offset has to be applied beforehand.
*/
function truncate( $number, $decimals )
{
$offset = '0.'. str_repeat( 0, $decimals ).'5';
return sprintf( "%.{$decimals}f", $number - $offset ); // Reduce $number by $offset and round
// appropriate by sprintf()
}
$number = 2.7172;
echo truncate( $number, 1 )."\r\n"; // 2.7
echo truncate( $number, 2 )."\r\n"; // 2.71
echo truncate( $number, 3 )."\r\n"; // 2.717
/**
* No problem either, if you need to number_format()
*/
$number = 112233445.566778899;
echo number_format( truncate( $number, 1 ), 1, ',', '.' )."\r\n"; // 112.233.445,5
echo number_format( truncate( $number, 2 ), 2, ',', '.' )."\r\n"; // 112.233.445,56
echo number_format( truncate( $number, 3 ), 3, ',', '.' )."\r\n"; // 112.233.445,566
?>