note 128399 added to function.number-format

From: Date: Sun, 16 Apr 2023 00:18:49 +0000
Subject: note 128399 added to function.number-format
Groups: php.notes 
Request: Send a blank email to php-notes+get-220353@lists.php.net to get a copy of this message
My simpler solution to the problem of the decimal number in this function being longer than the specified number of decimals. Standard result for number_format() is.. number_format(5.00098, 2) = 5.00 My function will return the result = 5.001 <?php // ** Warning: Does not work with scientific notation. Conversion to a real number is required. ** echo auto_decimal_format(5.0005620); // print 5.0006 echo auto_decimal_format(5.0009820); // print 5.001 echo auto_decimal_format(5.00098, 8); // print 5.00098000 echo auto_decimal_format(1.0295691366783E-5, 2); // print 0.00 function auto_decimal_format($n, $def = 2) { $a = explode(".", $n); if (count($a)>1) { $b = str_split($a[1]); $pos = 1; foreach ($b as $value) { if ($value != 0 && $pos >= $def) { $c = number_format($n, $pos); $c_len = strlen(substr(strrchr($c, "."), 1)); if ($c_len > $def) { return rtrim($c, 0); } return $c; // or break } $pos++; } } return number_format($n, $def); } ?> ---- Server IP: 45.112.84.4 Probable Submitter: 80.90.13.130 (proxied: 85.216.145.218) ---- Manual Page -- https://php.net/manual/en/function.number-format.php Edit -- https://main.php.net/note/edit/128399 Del: integrated -- https://main.php.net/note/delete/128399/integrated Del: useless -- https://main.php.net/note/delete/128399/useless Del: bad code -- https://main.php.net/note/delete/128399/bad+code Del: spam -- https://main.php.net/note/delete/128399/spam Del: non-english -- https://main.php.net/note/delete/128399/non-english Del: in docs -- https://main.php.net/note/delete/128399/in+docs Del: other reasons-- https://main.php.net/note/delete/128399 Reject -- https://main.php.net/note/reject/128399 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#220353) next »