|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
#1
|
|||
|
|||
|
I need to round a number, but I cannot find a function to round a number.
Ex: 156.8867 needs to be 156.89 Thanks, Jonathan Donaghe |
|
#2
|
|||
|
|||
|
Code:
my $longNumber = 156.8867; my $roundedNumber = sprintf "%.2f", $longNumber; print "The rounded number is : $roundedNumber\n"; Should round the number and print it to screen. sprintf is the command to use, the '2' in the arguments is the number of decimal places to round the number to. A '4' instead of the '2' would round to 4 decimals places. |
|
#3
|
|||
|
|||
|
I have this in place, but does not round the number
I have the number 976.755 and it rounds it to 976.75
Is there another way to round it? Thanks, Jonathan Donaghe |
|
#4
|
|||
|
|||
|
Opps, sorry, forgot a line. You should probably make this into a subroutine like this.
Code:
sub roundToTwoPlaces {
my $inptNumber = shift;
my $roundedNumber = sprintf "%.2f", $inptNumber;
$roundedNumber += .01;
return $roundedNumber;
}
AND/OR
sub roundToFourPlaces {
my $inptNumber = shift;
my $roundedNumber = sprintf "%.4f", $inptNumber;
$roundedNumber += .0001;
return $roundedNumber;
}
and then just call it with: my $number = roundToTwoPlaces('976.755'); Hope that helps. |
![]() |
| Viewing: Dev Shed Forums > Programming Languages > Perl Programming > How can I round a number |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|