简体   繁体   中英

How to make integer round off to hundredths place

In actionscript 3, I have a user enter a number into a field and this field is supposed to be for a cash value. How do I make it so that if for some reason they put say 20.956, it would round up to 20.96?

You could use toFixed() . Something like:

var cash:String = (Number("1.2365")).toFixed(2)

It's not mentioned in the documetnation, but i'm fairly sure it rounds rather than floors.

Notice that .toFixed() returns a string, if you want a more comprehensive helper then you could use something like the following.

    public function rounder(num:Number, decimalPlaces:int, method:Function = null):Number {
        if(method == null) method = Math.round;
        var mul:Number = Math.pow(10,decimalPlaces);
        return method(num * mul)/mul;
    }

and invoke it using:

rounder(1.245, 2); // returns 1.25  (it uses round by default)
rounder(1.245, 2, Math.floor); // returns 1.24
rounder(1.241, 2, Math.ceil); // returns 1.25

And actually you can use negative numbers for the decimalPlaces as well

rounder(2123, -1, Math.ceil); // returns 2130

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM