Question

i would remove the ending zeros with php_replace and i would have a better function like this.

Value:

$value = 123.12300;

Current function:

return preg_match('#[.,][0-9]+[0]+$#', $value) ? preg_replace('#[0]+$#', '', $value) : $value;

Another function:

return preg_replace('#([.,]{0,1}\d+)[0]+$#', '\\1', $value);

Thank you in advance!

Was it helpful?

Solution

[0-9]+, \d+ match greedily. (match as much as possible). It could match one of trailing 0. So use non-greedy version \d*?.

And [.,]{0,1} could make the pattern match even if that is no . or ,. Just use [.,].

$pattern = '#([.,]\d*?)0+$|[.,]$#';

var_dump(preg_replace($pattern, '\1', '123.12300'));
# => 123.123
var_dump(preg_replace($pattern, '\1', '1234000'));
# => 1234000
var_dump(preg_replace($pattern, '\1', '123456780.000000100'));
# => 123456780.0000001
var_dump(preg_replace($pattern, '\1', '123456780.'));
# => 123456780

OTHER TIPS

Simply use rtrim:

return rtrim($value,'0');

rtrim() will do the job

$value = 123.12300;
echo rtrim($value,'0');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top