Round off function

This function helps to round off the decimal number to the desired number of decimal points.

This is a more accurate method than toFixed() function of javascript.

  /************************************/
        //To round a float number
        /***********************************/
        function roundFloat(value, decimals) {
            decimals = (decimals) ? decimals : 2;
            return Number(Math.round(parseFloat(value) + 'e' + parseInt(decimals)) + 'e-' + parseInt(decimals));
        }

        /***************************************************/
        //To fix a float number to specified decimal parts
        /*************************************************/
        function fixFloat(value, decimals) {
            decimals = (decimals) ? decimals : 2;
            return roundFloat(parseFloat(value), parseInt(decimals)).toFixed(parseInt(decimals));
        }


THE FUNCTION CAN BE USED AS BELOW
var d=12.126
parseFloat(fixFloat(d,2)) // 2--> the decimal point precision
result : 12.13

Leave a comment

Your email address will not be published. Required fields are marked *