Alec
Alec

Reputation: 979

PHP Removes End Zeros?

Say I have

$number = .20

When I go to run the script, PHP automatically removes the zero, leaving just .2. How can this be fixed?

I know that .2 and .20 are the same, but what I am using this number for, I need the zero.

Upvotes: 3

Views: 109

Answers (5)

Matthew Flaschen
Matthew Flaschen

Reputation: 285077

.20 is a float literal. After it's parsed, it's converted to floating point. You can format it with two decimals later with:

sprintf("%.2f\n", $number);

But if you're not using it as a number at all, Mike is right that you should just keep it as a string.

Upvotes: 0

erm410
erm410

Reputation: 1024

The only think I can think of which requires the trailing 0s is displaying the number. .20 can be printed as follows:

// The number to display
$n = .2;

// The number of decimal places
$places = 2;

// Print the number to the desired precision.
echo number_format($n, $places)

Upvotes: 3

ose
ose

Reputation: 4085

You could format the number using:

$num_decimal_places = 2; // This will give .20
$formatted = number_format($number, $num_decimal_places, '.', '');

Upvotes: 1

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100205


$num = "0.20";
echo "Num is:".$num;

//OR
$num = number_format(0.20, 2);
echo "Num is:".$num;

Upvotes: 3

Mike B
Mike B

Reputation: 32165

You can make it a string

$number = '.20';

Upvotes: 2

Related Questions