Page 1 of 1

Truncate

Posted: Fri Dec 02, 2005 3:45 pm
by HiddenS3crets
Is there a function to truncate all the numbers after the decimal point so you're just left with a whole number?

ex: 105.643; truncated: 105

Posted: Fri Dec 02, 2005 3:51 pm
by RobertPaul

Code: Select all

$truncatedNumber = (int)$nonTruncatedNumber;

Posted: Fri Dec 02, 2005 3:53 pm
by foobar
Don't use type-casting, it's very unelegant.

Try this instead:

Code: Select all

$num = 105.643;

$truncated = intval($num);

Posted: Fri Dec 02, 2005 3:55 pm
by RobertPaul
Is there a difference, besides syntax?

[EDIT] Looked up intval() in TFM ... I suppose it is better than typecasting. :wink:

Posted: Fri Dec 02, 2005 5:04 pm
by Weirdan
using floor might be required because it returns float (which usually have bigger value range).

Posted: Fri Dec 02, 2005 5:18 pm
by John Cartwright
if you prefer to round, use round() even though it's not what you asked for, I thought it was worthy of a mention

Posted: Fri Dec 02, 2005 5:54 pm
by foobar
Since there's so many suggestions, I'm feeling compelled to do a really obsure one. :P

Code: Select all

$num = 105.43;

$pieces = split('.', "$num");

$truncated = $pieces[1];

echo $truncated;
...or an even more absurd one...

Code: Select all

$num = 105.43;

for ($i = 0; $i < strlen("$num"); $i++) {
 
  if ("$num"{i} == '.') break;

  $truncated .= intval("$num"{$i});
}

echo $truncated;

Posted: Fri Dec 02, 2005 6:09 pm
by Jenk
Your second snippet is so absurd it has parse errors!

Hint: it's $var{1} not "$var"{1} and you have missed out the dollar on the i :P

Posted: Fri Dec 02, 2005 6:19 pm
by foobar
Jenk wrote:Your second snippet is so absurd it has parse errors!

Hint: it's $var{1} not "$var"{1} and you have missed out the dollar on the i :P
Do I get bonus points for erroneous code? :P