First make sure $bar is numeric, then...
printf ("%.${bar}f", $foo / (10 ** $bar));
To deconstruct:
Take 10 to the power $bar to get the correct divisor. Then divide by it to move the decimal place over non-destructively. Then, to give the correct number of places, use printf and %. f -- note that there must be {} around bar because otherwise Perl will try to interpolate $barf, which, if you're using strict and have no variable called $barf will indeed barf. To get the string value rather than printing it out, use sprintf rather than printf.
So, for instance, if you have $foo being 570 and $bar being 1, you get (reducing the expression, so to speak):
printf ("%.${bar}f", $foo / (10 ** $bar))
printf ("%.1f", 570 / (10 ** 1))
printf ("%.1f", 570 / 10)
printf ("%.1f", 57)
"57.0"
... which is what you wanted I think. | [reply] [d/l] |
Do you want the decimals even if they aren't siginficant? 2 zeros aren't significant. if you change the number to 1555, it will print 15.55. It just drops non significant digits.
| [reply] |
yes I do. I understand 15 is the same as 15.00, but I need these zeros to remain in $foo's end result. The original digits in $foo must remain (i.e. $foo=1500 then result must have 1500 in it). I'm sorry, I did not try to use a different number in your script.
| [reply] |