Peter Bushnell
Peter Bushnell

Reputation: 928

Trimming trailing zeros WITHOUT casting to float

Let's try again but a bit more explicitly.

I am printing numbers to the screen and want to make them more friendly to users by stripping off trailing zeros after the decimal point. I have tried casting to a float but this solution is not a good fit as I handle numbers like 0.00000001 which come out along the lines of 0.1-e7 sort of thing which is unfriendly to end users.

I need a solution where number like the following...

12.02000000
12.00000000
0.00000001

...can be printed to the screen like...

12.02
12
0.00000001

Using rtim kills numbers like 10000. number_format needs to know the number of decimal places which may be from 0 to 8. Casting to float does not work. I'm sure that there is some regex for this.

Upvotes: 2

Views: 105

Answers (4)

Carlos
Carlos

Reputation: 5072

Here is a non-regex way to do it:

if (strpos($number, '.') !== false) {
    $number = rtrim($number, '.0');
}

Ternary operator style:

$number = strpos($number, '.') !== false ? rtrim($number, '.0') : $number;

Upvotes: 0

Explosion Pills
Explosion Pills

Reputation: 191749

A slightly simpler solution:

preg_replace("/(\.0*[^0]+)0*|\.0*/", '\1', $number)

Upvotes: 1

Sal00m
Sal00m

Reputation: 2916

After a bit of search for internet i found something that could be useful:

function floattostr( $val )
{
    preg_match( "#^([\+\-]|)([0-9]*)(\.([0-9]*?)|)(0*)$#", trim($val), $o );
    return $o[1].sprintf('%d',$o[2]).($o[3]!='.'?$o[3]:'');
}

This will give you the output you need i guess

I found here

Upvotes: 0

anubhava
anubhava

Reputation: 785108

Here is the regex solution as you want:

$repl = preg_replace('/(?>\.0+$|(\.\d*[^0])0+$)/', '$1', $numstr);

Testing:

echo preg_replace('/(?>\.0+$|(\.\d*[^0])0+$)/', '$1', '12.02000000') . "\n";
echo preg_replace('/(?>\.0+$|(\.\d*[^0])0+$)/', '$1', '12.00000000') . "\n";
echo preg_replace('/(?>\.0+$|(\.\d*[^0])0+$)/', '$1', '0.0000000100000000') . "\n";
echo preg_replace('/(?>\.0+$|(\.\d*[^0])0+$)/', '$1', '100000000') . "\n";

Output:

12.02
12
0.00000001
100000000

Upvotes: 3

Related Questions