Jay
Jay

Reputation: 751

How to round decimal place up?

I'm using the sprintf and printf function to round a decimal number, rounding down if hundredth position is less than 5, rounding up if hundredth position is greater than 5.

my $a = 1.12;
my $b = sprintf("%.1f", $a);
print "Unrounded: $a\nRounded: $b\n";
printf "Unrounded: $a\nRounded: %.1f\n", $a;

Is there a way to round up the decimal place up (e.g., $b = 1.2)?

Upvotes: 0

Views: 4517

Answers (2)

Borodin
Borodin

Reputation: 126722

You can use the ceil function from the core POSIX module to round up to the next integer. Factor your value by a power of ten before and after the operation to round up to a given number of decimal places

Also, don't use identifiers $a and $b; they are reserved for use by the sort built-in operator

use strict;
use warnings 'all';

use POSIX 'ceil';

my $aa = 1.12;
print "Unrounded:  $aa\n";

my $bb = sprintf("%.1f", $aa);
print "Rounded:    $bb\n";

my $cc = ceil($aa * 10) / 10;
print "Rounded up: $cc\n";

output

Unrounded:  1.12
Rounded:    1.1
Rounded up: 1.2

Upvotes: 3

Inian
Inian

Reputation: 85530

You can use the nhimult() function from the Math::Round library

nhimult TARGET, LIST

Returns the next higher multiple of the number(s) in LIST. TARGET must be positive. In scalar context, returns a single value; in list context, returns a list of values. Numbers that are between two multiples of the target will be adjusted to the nearest multiples of LIST that are algebraically higher. For example:

just do nhimult(0.1, $a) as

#!/usr/bin/perl

use Math::Round qw( :all );
my $a = 1.12;
my $b = sprintf("%.1f", $a);
print "Unrounded: $a\nRounded: $b\n";
printf "Unrounded: $a\nRounded: %.1f\n", $a;
printf "Unrounded: $a\nRounded: %.1f\n", $a;    
printf "Next higher multiple of $a: %.1f\n",  nhimult(0.1, $a);

produces

Unrounded: 1.12
Rounded: 1.1
Unrounded: 1.12
Rounded: 1.1
Unrounded: 1.12
Rounded: 1.1
Next higher multiple of 1.12, 1.2

You can get the Math::Round by doing

perl -MCPAN -e 'install Math::Round'

and import all the functions qw(:all).

Upvotes: 1

Related Questions