Sponsored Content
Top Forums Shell Programming and Scripting Rounding off decimals to the nearest number in PERL Post 302301431 by rikxik on Thursday 26th of March 2009 09:17:08 PM
Old 03-26-2009
From perlfaq

Quote:
Found in /usr/perl5/5.00503/pod/perlfaq4.pod
Does Perl have a round() function? What about ceil() and floor()? Trig functions?

Remember that int() merely truncates toward 0. For rounding to a
certain number of digits, sprintf() or printf() is usually the
easiest route.

printf("%.3f", 3.1415926535); # prints 3.142

The POSIX module (part of the standard perl distribution)
implements ceil(), floor(), and a number of other mathematical
and trigonometric functions.

use POSIX;
$ceil = ceil(3.5); # 4
$floor = floor(3.5); # 3

In 5.000 to 5.003 Perls, trigonometry was done in the
Math::Complex module. With 5.004, the Math::Trig module (part of
the standard perl distribution) implements the trigonometric
functions. Internally it uses the Math::Complex module and some
functions can break out from the real axis into the complex
plane, for example the inverse sine of 2.

Rounding in financial applications can have serious
implications, and the rounding method used should be specified
precisely. In these cases, it probably pays not to trust
whichever system rounding is being used by Perl, but to instead
implement the rounding function you need yourself.

To see why, notice how you'll still have an issue on half-way-
point alternation:

for ($i = 0; $i < 1.01; $i += 0.05) { printf "%.1f ",$i}

0.0 0.1 0.1 0.2 0.2 0.2 0.3 0.3 0.4 0.4 0.5 0.5 0.6 0.7 0.7
0.8 0.8 0.9 0.9 1.0 1.0

Don't blame Perl. It's the same as in C. IEEE says we have to do
this. Perl numbers whose absolute values are integers under
2**31 (on 32 bit machines) will work pretty much like
mathematical integers. Other numbers are not guaranteed.
 

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Rounding off to the next whole number

Hello, I searched a lot on this Forum. Please help me with the below problem. I want to divide two numbers and the result should be the next nearest whole number. E.G. Dividing 10.8/5 ideally gives 2.16. But the result should be 3 i.e. rounded off to the next whole number. Any help will... (2 Replies)
Discussion started by: damansingh
2 Replies

2. Shell Programming and Scripting

removing and rounding up decimals

Hi Experts, I have a command that gives me the output as below root@ckpgpay11core> cat sara | awk '{ sum += $1} ; END { print sum }' | awk {'print $1/90'} 8.88889 how do i remove the decimal spaces so that the figure will round itself to 9? Thanks. (3 Replies)
Discussion started by: aismann
3 Replies

3. Shell Programming and Scripting

convert Regular decimals to Packed decimals

Hi, I am trying to find if there is a way to convert regular decimal values to Paced decimal values. I tried to find a c program but I could get a Packed converted to regular decimal not the other way round. If not unix please let me know if any other progrimming language I can use to do... (2 Replies)
Discussion started by: mgirinath
2 Replies

4. Shell Programming and Scripting

rounding time in perl

Is there a way I can round time in perl to the nearest five minutes? For example if I have log giving the following time stamps 23,52,30 it would rounded up to 23,55,00 and 23,50,01 would be rounded to 23,50,00 (3 Replies)
Discussion started by: borderblaster
3 Replies

5. Shell Programming and Scripting

PERL - rounding fractional number

It seems that perl sprintf uses the round-to-even method: foreach my $i ( 0.5, 1.5, 2.5, 3.5 ) { printf "$i -> %.0f\n", $i; } __END__ 0.5 -> 0 1.5 -> 2 2.5 -> 2 3.5 -> 4 4.5 -> 4 Where we probably wants to use round-half-up, i.e. output should be as below: 0.5 -> 1 1.5 -> 2... (8 Replies)
Discussion started by: ganapati
8 Replies

6. Shell Programming and Scripting

AWK Match to nearest number

Hello Guys, I'm very new on here and require some help matching up and printing some columns using awk. I have two text files. The first file has Longitude data in column 1 (lon.txt) and the second one (node.txt) has again another Longitude data in column 1 (not exact as the first one) + in... (7 Replies)
Discussion started by: ian_gooch
7 Replies

7. Shell Programming and Scripting

Rounding number, but....

Dear Experts, I'm trying to find a way to round a number but in this way: 14367.577 ---> 14000 I used the following to round the number to the closer integer: echo $var|awk '{print int($1+0.5)}' and also: xargs printf "%1.0f" However, they don't work for my above... (9 Replies)
Discussion started by: Gery
9 Replies

8. UNIX for Dummies Questions & Answers

Rounding up to nearest whole number

Hi all of you, Would be great if you help me with how to round up to whole number from my input values like 2.99996,2.17890,3.00002,-2.3456,-2.7890 o/p should be like 3,2,3,-2,-3 thnks in adv!!!! regards (3 Replies)
Discussion started by: Indra2011
3 Replies

9. Shell Programming and Scripting

Rounding off to the nearest floating number

I have a number, which I want to convert into the nearest floating number upto two places after the decimal point. E.g. 1.2346 will become 1.23 but 1.2356 will become 1.24 . Similarly 0.009 will be 0.01 and 0.001 will be 0.00 or 0.0 (not 0, wnat to keep the decimal... (1 Reply)
Discussion started by: hbar
1 Replies

10. Shell Programming and Scripting

[awk] rounding a float number?

Heyas Trying to calculate the total size of a file by reading its bitrate. Code snippet: fs_expected() { # # Returns the expected filesize in bytes # pr_str() { ff=$(cat $TMP.info) d="${ff#*bitrate: }" echo "${d%%,*}" | $AWK '{print $1}' | head -n 1 } t_BYTERATE=$((... (9 Replies)
Discussion started by: sea
9 Replies
Decimal(3tcl)						  Tcl Decimal Arithmetic Library					     Decimal(3tcl)

__________________________________________________________________________________________________________________________________________________

NAME
::Decimal - General decimal arithmetic SYNOPSIS
package require Tcl ?8.5? ::Decimal::fromstr string ::Decimal::tostr decimal ::Decimal::setVariable variable setting ::Decimal::add a b ::Decimal::+ a b ::Decimal::subtract a b ::Decimal::- a b ::Decimal::multiply a b ::Decimal::* a b ::Decimal::divide a b ::Decimal::/ a b ::Decimal::divideint a b ::Decimal::remainder a b ::Decimal::abs decimal ::Decimal::compare a b ::Decimal::max a b ::Decimal::maxmag a b ::Decimal::min a b ::Decimal::minmag a b ::Decimal::plus a ::Decimal::minus a ::Decimal::copynegate a ::Decimal::copysign a b ::Decimal::is-signed decimal ::Decimal::is-zero decimal ::Decimal::is-NaN decimal ::Decimal::is-infinite decimal ::Decimal::is-finite decimal ::Decimal::fma a b c ::Decimal::round_half_even decimal digits ::Decimal::round_half_up decimal digits ::Decimal::round_half_down decimal digits ::Decimal::round_down decimal digits ::Decimal::round_up decimal digits ::Decimal::round_floor decimal digits ::Decimal::round_ceiling decimal digits ::Decimal::round_05up decimal digits _________________________________________________________________ DESCRIPTION
The decimal package provides decimal arithmetic support for both limited precision floating point and arbitrary precision floating point. Additionally, integer arithmetic is supported. More information and the specifications on which this package depends can be found on the general decimal arithmetic page at http://speleotrove.com/decimal This package provides for: o A new data type decimal which is represented as a list containing sign, mantissa and exponent. o Arithmetic operations on those decimal numbers such as addition, subtraction, multiplication, etc... Numbers are converted to decimal format using the operation ::Decimal::fromstr. Numbers are converted back to string format using the operation ::Decimal::tostr. EXAMPLES
This section shows some simple examples. Since the purpose of this library is to perform decimal math operations, examples may be the sim- plest way to learn how to work with it and to see the difference between using this package and sticking with expr. Consult the API section of this man page for information about individual procedures. package require decimal # Various operations on two numbers. # We first convert them to decimal format. set a [::Decimal::fromstr 8.2] set b [::Decimal::fromstr .2] # Then we perform our operations. Here we multiply set c [::Decimal::* $a $b] # Finally we convert back to string format for presentation to the user. puts [::Decimal::tostr $c] ; # => will output 8.4 # Other examples # # Subtraction set c [::Decimal::- $a $b] puts [::Decimal::tostr $c] ; # => will output 8.0 # Why bother using this instead of simply expr? puts 8.399999999999999 ; # => will output 8.399999999999999 puts 7.999999999999999 ; # => will output 7.999999999999999 # See http://speleotrove.com/decimal to learn more about why this happens. API
::Decimal::fromstr string Convert string into a decimal. ::Decimal::tostr decimal Convert decimal into a string representing the number in base 10. ::Decimal::setVariable variable setting Sets the variable to setting. Valid variables are: o rounding - Method of rounding to use during rescale. Valid methods are round_half_even, round_half_up, round_half_down, round_down, round_up, round_floor, round_ceiling. o precision - Maximum number of digits allowed in mantissa. o extended - Set to 1 for extended mode. 0 for simplified mode. o maxExponent - Maximum value for the exponent. Defaults to 999. o minExponent - Minimum value for the exponent. Default to -998. ::Decimal::add a b ::Decimal::+ a b Return the sum of the two decimals a and b. ::Decimal::subtract a b ::Decimal::- a b Return the differnece of the two decimals a and b. ::Decimal::multiply a b ::Decimal::* a b Return the product of the two decimals a and b. ::Decimal::divide a b ::Decimal::/ a b Return the quotient of the division between the two decimals a and b. ::Decimal::divideint a b Return a the integer portion of the quotient of the division between decimals a and b ::Decimal::remainder a b Return the remainder of the division between the two decimals a and b. ::Decimal::abs decimal Return the absolute value of the decimal. ::Decimal::compare a b Compare the two decimals a and b, returning 0 if a == b, 1 if a > b, and -1 if a < b. ::Decimal::max a b Compare the two decimals a and b, and return a if a >= b, and b if a < b. ::Decimal::maxmag a b Compare the two decimals a and b while ignoring their signs, and return a if abs(a) >= abs(b), and b if abs(a) < abs(b). ::Decimal::min a b Compare the two decimals a and b, and return a if a <= b, and b if a > b. ::Decimal::minmag a b Compare the two decimals a and b while ignoring their signs, and return a if abs(a) <= abs(b), and b if abs(a) > abs(b). ::Decimal::plus a Return the result from ::Decimal::+ 0 $a. ::Decimal::minus a Return the result from ::Decimal::- 0 $a. ::Decimal::copynegate a Returns a with the sign flipped. ::Decimal::copysign a b Returns a with the sign set to the sign of the b. ::Decimal::is-signed decimal Return the sign of the decimal. The procedure returns 0 if the number is positive, 1 if it's negative. ::Decimal::is-zero decimal Return true if decimal value is zero, otherwise false is returned. ::Decimal::is-NaN decimal Return true if decimal value is NaN (not a number), otherwise false is returned. ::Decimal::is-infinite decimal Return true if decimal value is Infinite, otherwise false is returned. ::Decimal::is-finite decimal Return true if decimal value is finite, otherwise false is returned. ::Decimal::fma a b c Return the result from first multiplying a by b and then adding c. Rescaling only occurs after completion of all operations. In this way the result may vary from that returned by performing the operations individually. ::Decimal::round_half_even decimal digits Rounds decimal to digits number of decimal points with the following rules: Round to the nearest. If equidistant, round so the final digit is even. ::Decimal::round_half_up decimal digits Rounds decimal to digits number of decimal points with the following rules: Round to the nearest. If equidistant, round up. ::Decimal::round_half_down decimal digits Rounds decimal to digits number of decimal points with the following rules: Round to the nearest. If equidistant, round down. ::Decimal::round_down decimal digits Rounds decimal to digits number of decimal points with the following rules: Round toward 0. (Truncate) ::Decimal::round_up decimal digits Rounds decimal to digits number of decimal points with the following rules: Round away from 0 ::Decimal::round_floor decimal digits Rounds decimal to digits number of decimal points with the following rules: Round toward -Infinity. ::Decimal::round_ceiling decimal digits Rounds decimal to digits number of decimal points with the following rules: Round toward Infinity ::Decimal::round_05up decimal digits Rounds decimal to digits number of decimal points with the following rules: Round zero or five away from 0. The same as round-up, except that rounding up only occurs if the digit to be rounded up is 0 or 5, and after overflow the result is the same as for round- down. BUGS, IDEAS, FEEDBACK This document, and the package it describes, will undoubtedly contain bugs and other problems. Please report such in the category Decimal of the Tcllib SF Trackers [http://sourceforge.net/tracker/?group_id=12883]. Please also report any ideas for enhancements you may have for either package and/or documentation. KEYWORDS
decimal, math, tcl CATEGORY
Mathematics COPYRIGHT
Copyright (c) 2011 Mark Alston <mark at beernut dot com> math 1.0.2 Decimal(3tcl)
All times are GMT -4. The time now is 02:27 AM.
Unix & Linux Forums Content Copyright 1993-2022. All Rights Reserved.
Privacy Policy