Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Drop decimal places without rounding

Status
Not open for further replies.

dyedblue

Technical User
Aug 20, 2004
11
0
0
US
I am currently use the number_format PHP function but I do not want it to round my number at 2 decimal places. I need it to cut off all numbers past 2 decimal places with no rounding. I have searched hard for other functions that might work such as Round but had no luck making it work. Could someone please help me?

Current Code:
Code:
$amtr1 = 3,750.945; 
$amt1 = number_format($amtr1, 2, '.', ',');
$amt1 comes out as "3,750.95 I need $amt1 to come out as "3,750.94" instead.

Thanks in advance
 
<?php
$amtr1 = 3,750.945;
$last = $amtr1{strlen($amtr1)-1};
$amtr = rtrim($amtr1, "$last");
print "$amtr";
?>

There's probably a simpler/quicker solution using ereg_replace though.

 
Its not very nice , but this should do what you want:

Code:
function cut_off($number){
$parts=explode(".",$number);
$newnumber=$parts[0]. "." . $parts[1][0] . $parts[1][1];
return $newnumber;
}

Just pass it the variable containing the number you wish to cutoff.





----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.
 
This one might be a little nicer:

Code:
$newnumber=substr($number,0,(strpos($number,".")+1)+2);

And J1mbo, your's only works if there are exactly 3 decimal places what happens if there are only 2 or 5.



----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.
 
Here's my preg_replace solution:

$amtr1 = "3,750.945";
$amtr1 = preg_replace('/([\d,]+.\d{2})\d/', '$1', $amtr1);
print "$amtr1";

 
This one handles whatever number of numbers occur after the decimal:

$amtr1 = "3,750.94545645";
$amtr1 = preg_replace('/([\d,]+.\d{2})\d+/', '$1', $amtr1);
print "$amtr1";


 
Thanks that worked great, you guys are awesome.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top