Wednesday 29 August 2018

JavaScript: Rounding float values

‘floor’, ‘ceil’, ‘round’ functions are used to perform rounding on float values.

Function
Description
Math.floor(number)
Get the floor value of a number.
Math.ceil(number)
Get the ceil value of a number.
Math.round(number)
Round the number to nearest integer.

var a = Math.floor(5.9);         // Return 5
var b = Math.ceil(5.1);          // Return 6
var c = Math.round(5.4);       // Return 5
var d = Math.round(5.5);       // Return 6

round.html
<!DOCTYPE html>

<html>

<head>
    <title>rounding example</title>
</head>

<body>
    <script type="text/javascript">
        var a = Math.floor(5.9); // Return 5
        var b = Math.ceil(5.1); // Return 6
        var c = Math.round(5.4); // Return 5
        var d = Math.round(5.5); // Return 6

        document.write("a = " + a + "<br />");
        document.write("b = " + b + "<br />");
        document.write("c = " + c + "<br />");
        document.write("d = " + d + "<br />");
    </script>
</body>

</html>


Previous                                                 Next                                                 Home

No comments:

Post a Comment