Atasha
Atasha

Reputation: 499

How to trim leading and trailing zeros in a number in PHP

I have the following numbers:

  000000006375 and I want to output 63.75
  000000004500 and I want to output just 45

Basically, if the last two numbers are not zero, I wanted to make it a float value wherein a decimal point will be added. But if the last 2 numbers are zeros I just want to output a whole number which in the example is just 45.

I was thinking of casting the numbers to int first but I do not know how to convert it to a float number if there last 2 digits are non-zeros.

Upvotes: 1

Views: 394

Answers (5)

tux
tux

Reputation: 1287

$int = (int)'000000004500';
echo round((substr($int, 0, -2) . '.' . substr($int, -2)),2);

This is one way to do it :)

Upvotes: 0

Susheel
Susheel

Reputation: 1679

print round('000000006375'/100,2);
print '<br/>';
print round('000000004500'/100,2);

Upvotes: 0

Bjoern
Bjoern

Reputation: 16314

For your use case you might just cast it into an integer and divide with 100, like this:

$t1 = "000000006375";
$t2 = "000000004500";

var_dump(myfunc($t1), myfunc($t2));

function myfunc($in) {
    $out = (int) $in / 100;
    return $out;
}

The output will be something like...

float(63.75) 
int(45) 

Upvotes: 0

anubhava
anubhava

Reputation: 786359

You can use this code:

$s = '000000006375';
$i = (int) $s /100; // 63.75

Upvotes: 2

Nabil Kadimi
Nabil Kadimi

Reputation: 10424

echo "000000006375" / 100;
echo '<br />';
echo "000000004500" / 100;


// Output: 63.75<br />45

Upvotes: 1

Related Questions