Skip to main content
Known Participant
March 6, 2010
Answered

PHP - number_format question

  • March 6, 2010
  • 1 reply
  • 1676 views

I want to format a number without rounding it.  For example, I have a number that is 5.77890 and I just want to drop the 7890 and display 5.7, but without rounding it up.  Right now I am using number_format but it's rounding it to 5.8.  How can this be done?

This topic has been closed for replies.
Correct answer David_Powers

David,

I copied this code, into a blank document and still got a T_Variable error?


I don't see how you can get an error by running that code. Here is a screenshot of it running in Live View. You can see the output "3.3" in Design view.

I have also attached the original PHP code.

1 reply

David_Powers
Inspiring
March 6, 2010

If you don't want the number to be rounded up, you will need to use string manipulation functions to achieve what you want. The following custom function will do it for you:

function stripNum($num, $decplaces = 1) {
  $pos = strpos($num, '.');
  return substr($num, 0, $pos+1+$decplaces);
}

This finds the decimal point, and returns the value truncated to the number of decimal places specified by the second (optional) argument.

$original = 5.77890;

echo stripNum($original);   // displays 5.7

echo stripNum($original, 2) // displays 5.77

If there's no decimal point, you just get the original number.

Known Participant
March 6, 2010

David, I tried this below and am getting a T_Variable error on the line $pos

= strops($num, '.'); HERE is my code:

<?php function stripNum($num, $decplaces = 1) {

  $pos = strpos($num, '.');

  return substr($num, 0, $pos1$decplaces); }

if ($row_getCountin12['countin12'] >= 20) {

if (((($row_getHandi['sum_hand']) - ($row_getTourd['handi'])) < 3))

{

echo stripNum($row_getHandi['sum_hand']);

}

} ?>

Thanks.

David_Powers
Inspiring
March 6, 2010

rickpick77665 wrote:

  return substr($num, 0, $pos1$decplaces); }

You have got this:

$pos1$decplaces

It should be:

$pos+1+$decplaces

Or if you prefer to spread things out:

$pos + 1 + $decplaces