Jump to content

Php Calculation Decimal Format


computermax2328

Recommended Posts

Hello Everyone,

 

Haven't been here in a while. This looks new and cool!

 

Anyway, I have PHP output an array of numbers as an average and that worked fine. I got the number -.0111523. Which is exactly what I want. They only problem is that I need the number to look like this -.011. I tried to use the number format command, but that did not work. Just slapped a couple of zeros onto the end.

 

Any suggestions?

 

Thanks in advance!

Link to comment
https://forums.phpfreaks.com/topic/268854-php-calculation-decimal-format/
Share on other sites

Formatting a float less than 1 is going to give a zero before the decimal point so you will need to remove it yourself. Something like

 

<?php
$n = -.0111523;
$nstr = number_format($n, 3);
if (abs($n < 1)) {
   $nstr = str_replace('0.', '.', $nstr);
}
echo $nstr;
?>

$avg = "SELECT AVG(era) FROM $table";
$avgquery = mysql_query($avg, $connection);
while($avgrow = mysql_fetch_array($avgquery)) {
$avgera = $avgrow['AVG(era)'];
}
echo number_format(decimals($avgera), 3, ".", ",");


 

Gives me -.0111523.00

 

decimals is a function that uses str_replace to strip the zero from the front of the decimal number.

number_format does what you want, but it puts a 0 before the decimal.

 

If you wish to remove it, you should wrap your decimals() function AROUND the number_format function. Functions in programming languages are called inside-out, the innermost ones are resolved first.

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.