Ads removed from the pastie. \o/
Running costs stayed. :-(
Donations welcome!

Bitcoin: 1QC38uPBSy7WSYz1whM5SYTHAdhqkN6o8V
Ethereum: 0x0855778a6181a69cc7d5d08c71c4f5846010eb67
Verge: D8fo1fszrNmUK4kfQW5owhYMv3osPvgn2g
Recent entries
2020-09-23 11:38:59
full watch
2020-09-23 11:30:11
wallet access
2020-09-23 11:29:17
takurisen
2020-09-23 11:29:08
movies hd
2020-09-23 11:29:06
No title specified
2020-09-23 11:24:06
No title specified
2020-09-23 11:22:49
No title specified
2020-09-23 11:22:32
No title specified
2020-09-23 11:22:14
No title specified
2020-09-23 11:22:03
full watch
Permanent entries
2014-10-14 21:12:28
Boost property tree - Ite...
2013-10-18 08:24:21
Resize images in a folder...
2013-04-29 17:23:35
Find bad words in a text,...
2013-02-12 20:26:45
Merge two boost property ...
2012-12-18 16:21:40
OpenCV: Access/modify ima...
2012-11-19 10:48:40
Reading a boost::property...
2012-04-10 00:11:46
Convert hex to string or ...
2012-02-18 00:12:04
Screw up []-operator for ...
2012-02-16 03:02:24
Merge continuous numbers ...
2012-01-18 22:26:01
(PHP) Generate / Create (...
2011-04-19 16:05:25
Calculate one's age in ye...
2011-04-18 15:26:45
(PHP) Generate / Create r...
2010-08-26 15:18:00
Pick the first element (k...
2010-07-28 10:36:45
Quakenet - Snailbot comma...
2010-06-21 21:30:52
Using the MATLAB profiler...
2010-05-31 06:31:14
PHP truncation function
2010-05-06 20:49:26
Quakenet - Fishbot comman...
Paste ID: # d3798
Date posted: Mon, 31 May 2010 06:31:14 +0000
Date of expiration: never (permanent entry)
Description:

PHP truncation function

  1. <?php
  2. /**
  3.  * sprintf() does normal rounding. To achieve a truncation an appropriate offset has to be applied beforehand.
  4.  */
  5. function truncate( $number, $decimals )
  6. {
  7.   $offset = '0.'. str_repeat( 0, $decimals ).'5';
  8.   return sprintf( "%.{$decimals}f", $number - $offset ); // Reduce $number by $offset and round appropriate by sprintf()
  9. }
  10.  
  11. $number = 2.7172;
  12.  
  13. echo truncate( $number, 1 )."\r\n"; // 2.7
  14. echo truncate( $number, 2 )."\r\n"; // 2.71
  15. echo truncate( $number, 3 )."\r\n"; // 2.717
  16.  
  17. /**
  18.  * No problem either, if you need to number_format()
  19.  */
  20. $number = 112233445.566778899;
  21.  
  22. echo number_format( truncate( $number, 1 ), 1, ',', '.' )."\r\n"; // 112.233.445,5
  23. echo number_format( truncate( $number, 2 ), 2, ',', '.' )."\r\n"; // 112.233.445,56
  24. echo number_format( truncate( $number, 3 ), 3, ',', '.' )."\r\n"; // 112.233.445,566
  25. ?>
You can paste a correction or amendment to the upper paste or a new paste down below.