Formating integer values

They have: 19 posts

Joined: Oct 2000

Hi,

Can anyone tell me a very simple way of formatting an integer value to a specified number of decimal places?

Thanks,

Denise Smiling

They have: 161 posts

Joined: Dec 1999

First, define "round". Which of the following do you mean:

"floor": -1.1 gets rounded to -2, -1.9 gets rounded to -2, 1.1 gets rounded to 1, 1.9 gets rounded to 1

"ceil": -1.1 gets rounded to -1, -1.9 gets rounded to -1, 1.1 gets rounded to 2, 1.9 gets rounded to 2

"int": -1.1 gets rounded to -1, -1.9 gets rounded to -1, 1.1 gets rounded to 1, 1.9 gets rounded to 1

"nearest": -1.1 gets rounded to -1, -1.9 gets rounded to -2, 1.1 gets rounded to 1, 1.9 gets rounded to 2

When you've told me what you mean, I can offer some specific help and code.

They have: 19 posts

Joined: Oct 2000

Hi,

I mean, say I generate a number value of "2.67653" and want to round it "2.7" or "2.68" etc...

Denise

They have: 453 posts

Joined: Jan 1999

$x = 2.67653;
$x1 = int($x * 10 + 0.5)/10;
$x2 = int($x * 100 + 0.5)/100;
'

Untested, but should work.

They have: 161 posts

Joined: Dec 1999

So, given a number of decimal places, you want to round to the nearest value. So, 1.345 rounded to ONE place would be 1.3, but rounded to TWO places would be 1.35, right?

sub round {
  my ($n,$pl) = (@_,0);
  my $fact = 10**$pl;
  return $n > 0 ?
    int($n * $fact + .5)/$fact :
    -int(-$n * $fact + .5)/$fact;
}
'

It expects you give it a non-negative integer for the value of decimal places to round it to. Calling it as round($x) will round it to an integer; calling it as round($x,$N) will round it to $N decimal places.

They have: 19 posts

Joined: Oct 2000

Cheers Guys,

I'll give these a try!

Denise Smiling

merlin's picture

They have: 410 posts

Joined: Oct 1999

hu, i have quite the same question (now that you're talking about... Wink ) :
i have an integer like 10 or 10.5 and i'd like to display it with two decimals: 10.00 (10.50)
so, it's not less a rounding question than a display-thing...

They have: 19 posts

Joined: Oct 2000

Hi, someone helped me in another forum and I think this may well work, although I am yet to try it out.

$formatted_num = sprintf("%.2f", $original_num);

I guess just change "%.2f" to the number of decimal places you need, ie: "%.3f" for three decimal places.

Denise

merlin's picture

They have: 410 posts

Joined: Oct 1999

thank you, i'll try it...
Smiling

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.