Truncate

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
HiddenS3crets
Forum Contributor
Posts: 119
Joined: Fri Apr 22, 2005 12:23 pm
Location: USA

Truncate

Post 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
RobertPaul
Forum Contributor
Posts: 122
Joined: Sun Sep 18, 2005 8:54 pm
Location: OCNY

Post by RobertPaul »

Code: Select all

$truncatedNumber = (int)$nonTruncatedNumber;
foobar
Forum Regular
Posts: 613
Joined: Wed Sep 28, 2005 10:08 am

Post by foobar »

Don't use type-casting, it's very unelegant.

Try this instead:

Code: Select all

$num = 105.643;

$truncated = intval($num);
RobertPaul
Forum Contributor
Posts: 122
Joined: Sun Sep 18, 2005 8:54 pm
Location: OCNY

Post by RobertPaul »

Is there a difference, besides syntax?

[EDIT] Looked up intval() in TFM ... I suppose it is better than typecasting. :wink:
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post by Weirdan »

using floor might be required because it returns float (which usually have bigger value range).
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post 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
foobar
Forum Regular
Posts: 613
Joined: Wed Sep 28, 2005 10:08 am

Post 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;
User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

Post 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
foobar
Forum Regular
Posts: 613
Joined: Wed Sep 28, 2005 10:08 am

Post 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
Post Reply