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 Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

rounding

Status
Not open for further replies.

mover50

Programmer
Aug 3, 2004
77
0
0
US
Say I do a calculation that has a variable with a whole number and another with a floating point. Say the numbers are, 2 and 14.897 and I multiply them 2*14.897 which equals 29.794, however I want to round it up to 29.8. How would I do that?

Thanks,



Kent (the worrier)
 
To round 29.794 to 29.8, you would multiply by 10, round to the nearest integer, then divide by 10. To do rounding, add 0.5 (or subtract 0.5 if number is negative) and then truncate. So:

Code:
if ($x < 0) {
  $xR = int (($x * 10) - 0.5) / 10;
} else {
  $xR = int (($x * 10) + 0.5) / 10;
}
 
Isn't there a simple way to set a scaler value for a variable that for example says, $testfield is a numercial field 4 chars long with 2 dec positions?

Thanks,

Kent (the worrier)
 
I found a partial answer, the printf command.
Still, I would like to just be able to store a floating point numerical variable specifying it with a limited number of decimal places.

Thanks,


Kent (the worrier)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top