php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #79471 new function
Submitted: 2020-04-13 09:48 UTC Modified: 2020-04-13 14:04 UTC
From: festuc at lestudi dot com Assigned:
Status: Not a bug Package: Strings related
PHP Version: 7.4.5RC1 OS: any
Private report: No CVE-ID: None
 [2020-04-13 09:48 UTC] festuc at lestudi dot com
Description:
------------
---
From manual page: https://php.net/function.number-format
---
Your number_format don't trim unnecesary zeros at left integer part or rigth decimal part. Humans brain read 58 58.1 when you put 00058.0000, 0058.1000 So, why no have a function for write 58 or 58.1 directly with a function?

Test script:
---------------
<?php 
function number_format_trim($value,$maxdecimal=0,$decimalsing='.',$thousandsing=','){
	if (is_numeric($value)){
		$value=number_format($value,$maxdecimal,'.','');//to change input type to string
		$i=-1;
		if (strpos($value,'.'))while (substr($value,$i)==0){
			$i--;
			$maxdecimal--;
		}
		else $maxdecimal=0;
		return number_format($value,$maxdecimal,$decimalsing,$thousandsing);
	}
}
//example code:
$decimalsing=','; //french mode
$thousandsing=' ';
$a = array (10000/3,10.15000,'00058.0000',1.01000,'pastafarism','1001.00100',30.05,25/2,'0.2500','potato');
foreach ($a as $w){
	unset($o);
	$o=number_format_rtrim($w,5,$decimalsing,$thousandsing);
	if(isset($o))
		echo "$w: $o";
	else
		echo "$w is not a number";
	echo '<br/>';
}
?>
result is:
3333.3333333333: 3 333,33333
10.15: 10,15
00058.0000: 58
1.01: 1,01
pastafarism is not a number
1001.00100: 1 001,001
30.05: 30,05
12.5: 12,5
0.2500: 0,25
potato is not a number

Expected result:
----------------
a new function

Actual result:
--------------
number_format do what need to do, but sometimes we need trim unnecesary zeros at rigth too

Patches

number_format_trim (last revision 2020-04-13 09:50 UTC by festuc at lestudi dot com)

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2020-04-13 09:50 UTC] festuc at lestudi dot com
The following patch has been added/updated:

Patch Name: number_format_trim
Revision:   1586771457
URL:        https://bugs.php.net/patch-display.php?bug=79471&patch=number_format_trim&revision=1586771457
 [2020-04-13 14:04 UTC] requinix@php.net
-Status: Open +Status: Not a bug -Package: Unknown/Other Function +Package: Strings related
 [2020-04-13 14:04 UTC] requinix@php.net
rtrim(number_format($value, $maxdecimal), "0")
 
PHP Copyright © 2001-2020 The PHP Group
All rights reserved.
Last updated: Mon Sep 28 13:01:23 2020 UTC