Javascript

Round off decimal values using JS

Round off decimal values using JS

JS => There are four functions available to round off a decimal value
1) Exact round off ( if x > 0.5 then taken as x=1 and x < 0.5 then taken as x=0 )
2) Rounded up to nearest integer ( if x > 0 then taken as x=1 and x < 0 then taken as x=0 )
3) Rounded down to nearest integer ( if x > 1 then taken as x=1 and x < 1 then taken as x=0 )
4) Round off to given precision of decimal points

1) syntax: Math.round(number);
Example: <script> var x=123.51; var y=110.49;
alert(” Result = “+Math.round(x) ); // Result = 124
alert(” Result = “+Math.round(y) ); // Result = 110
</script>

2) syntax: Math.ceil(number);
Example: <script> var x=123.51; var y=110.49;
alert(” Result = “+Math.ceil(x) ); // Result = 124
alert(” Result = “+Math.ceil(y) ); // Result = 111
</script>

3) syntax: Math.floor(number);
Example: <script> var x=123.51; var y=110.49;
alert(” Result = “+Math.floor(x) ); // Result = 123
alert(” Result = “+Math.floor(y) ); // Result = 110
</script>

4) syntax: element.toFixed(precision); precision=> 0 to 99
Example: <script> var x=123.523141511; var y=110.4988711;
alert(” Result = “+x.toFixed(5) ); // Result = 123.52314
alert(” Result = “+y.toFixed(2) ); // Result = 110.50
</script>

 

Tagged , , , , ,

Leave a Reply