in reply to Help with decimals

Rich,

When I run your script I get "15" not "15.00"

if $foo = 1500 and...
if $bar = 4 then the result should be .1500
if $bar = 3 then the result should be 1.500
if $bar = 2 then the result should be 15.00
if $bar = 1 then the result should be 150.0
if $bar = 0 then the result should be 1500

another example if $foo = 12653 and...
if $bar = 4 then the result should be 1.2653
if $bar = 3 then the result should be 12.653
if $bar = 2 then the result should be 126.53
if $bar = 1 then the result should be 1265.3
if $bar = 0 then the result should be 12653

Again, this is why I thought of it as "lets put add a dot to $foo at $bar+1 from the right (I don't know how to code that)"
as opposed to lets multiply $foo by .01 or .001 etc.

Replies are listed 'Best First'.
Re: Re: Help with decimals
by premchai21 (Curate) on Jul 30, 2001 at 08:12 UTC
    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):

    1. printf ("%.${bar}f", $foo / (10 ** $bar))
    2. printf ("%.1f", 570 / (10 ** 1))
    3. printf ("%.1f", 570 / 10)
    4. printf ("%.1f", 57)
    5. "57.0"
    ... which is what you wanted I think.
Re: Re: Help with decimals
by rchiav (Deacon) on Jul 30, 2001 at 08:03 UTC
    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.
      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.