On Wed, Mar 26, 2008 at 05:16:56PM +0100, Arvin Schnell wrote:
> 
> Hi Protectors Of YCP,
> 
> which is the easiest way to display a float with 3 digits after
> the decimal point and rounding to zero?

Piece of, er, cake. Attached.

-- 
Martin Vidner, YaST developer
http://en.opensuse.org/User:Mvidner

Kuracke oddeleni v restauraci je jako fekalni oddeleni v bazenu
{
        string f(float a) {
                // trim excess precision
                const float factor = 1000;
                integer r = tointeger (a * factor); // round to zero
                string s = tostring (r / factor);
                // now pad with zeros
                if (true) {
                    // assert(s contains ".");
                    // 1000. -> 1000 -> "1000" -> "000"
                    const string pad = substring (tostring (tointeger 
(factor)), 1);
                    const integer padlen = size (pad);
                    s = s + pad;
                    s = substring (s, 0, search (s, ".") + padlen + 1);
                }
                return s;
        }

        foreach (float a, [
                        3.14,
                        3.94,
                        -3.14,
                        -3.94,
                        0.0,
                        1.0,
                        1000.0,
                        0.123456,
                        0.777777,
                        -0.123456,
                        -0.777777,
                        ], {
                y2milestone ("%1 : '%2'", a, f(a));
        });
}

Reply via email to