Formating integer values
Hi,
Can anyone tell me a very simple way of formatting an integer value to a specified number of decimal places?
Thanks,
Denise
Hi,
Can anyone tell me a very simple way of formatting an integer value to a specified number of decimal places?
Thanks,
Denise
japhy posted this at 01:42 — 9th November 2000.
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.
Denise posted this at 02:45 — 9th November 2000.
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
anti posted this at 11:08 — 9th November 2000.
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.
japhy posted this at 12:53 — 9th November 2000.
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.
Denise posted this at 15:07 — 9th November 2000.
They have: 19 posts
Joined: Oct 2000
Cheers Guys,
I'll give these a try!
Denise
merlin posted this at 16:30 — 9th November 2000.
They have: 410 posts
Joined: Oct 1999
hu, i have quite the same question (now that you're talking about... ) :
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...
Denise posted this at 17:16 — 9th November 2000.
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 posted this at 06:18 — 10th November 2000.
They have: 410 posts
Joined: Oct 1999
thank you, i'll try it...
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.