supermoney
supermoney

Reputation: 79

Format a decimal number in PHP

I'm trying to format specific numbers up to 8 decimals by deleting unnecessary zeros.

My actual code is:

rtrim(sprintf("%.8f", $upto_eight_decimals), '0')

It actually prevents to format a number as 0.00012 into 1.2E-4 or 0.00012000

However, with numbers integer such as 1 it gets converted into 1. but this point is not my expected result (I know because of rtrim deleting all zeros).

UPDATE: rtrim(rtrim(sprintf("%.8f", $upto_eight_decimals), '0'), '.') it looks like working

Upvotes: 0

Views: 335

Answers (1)

Murad Hasan
Murad Hasan

Reputation: 9583

You can do it this way, Just use number_format:

$upto_eight_decimals = "0.0001200";
$out = number_format((float)$upto_eight_decimals, 8, '.', '');

echo preg_replace("/\.?0*$/",'',$out);
or
echo $out + 0;

This function returns a string.

This will work for you, let me know is it work or not.

Upvotes: 1

Related Questions