in reply to How to get rounded numbers to =100% ??

Don't trust sprintf(). For whatever whim people had, it has some very arbitrary ideas about how to round numbers. On some platforms, it rounds 0.5 down, but 1.5 up. I did a test on Solaris and Windows, and the results varied. (Both versions just rely on their C runtime implementations of sprintf().)

If you care about numbers, do the math yourself. Learn how floating point numbers on computers work, and where they're likely to introduce problems. For example, you're forcing a division before a multiplication in your loop. This reduces precision in floating point numbers. It's better to say $percent = ($x * 100 / $y);.

Once you've got the floating value, use $rounded = int($unrounded + ($unrounded <=> 0)*0.5);. (This uses the spaceship operator like a sgn() function.)

--
[ e d @ h a l l e y . c c ]

Replies are listed 'Best First'.
Re: Re: How to get rounded numbers to =100% ??
by hossman (Prior) on May 23, 2003 at 02:05 UTC
    If you care about numbers, do the math yourself. Learn how floating point numbers on computers work, and where they're likely to introduce problems.

    The problem there being: to understand how floating point numbers on computers work, you have to understand how your particular architecture deals with floating point numbers -- as well as every other architecture your program might run on.

    (There are multiple IEEE floating point standards, not to mention that a lot of hardware doesn't do any of them right)

    I would suggest, in the spirit of your orriginal suggestion, that if you really care about precission, the best thing to do is to use an existing module designed to allow cross platform support for very precise mathematic operators (like Math::BigFloat) and if you really care about how the internals work, read the source.

Re: Re: How to get rounded numbers to =100% ??
by alarix (Initiate) on May 22, 2003 at 14:51 UTC
    Floating point numbers ... I just did a quick search. perhaps something like this tutorial? (opens a new window) ... which, by the way, is the first time I've opened an applet that didn't crash my browser.