Math And Rounding In JavaScript: Hello everyone, welcome to the nkcoderz.com website. In this article we will going to discuss about the Math And Rounding In JavaScript.
Math And Rounding In JavaScript
JavaScript provides several built-in methods for performing mathematical operations and rounding numbers.
Here are some of the most commonly used mathematical operations in JavaScript:
- Addition:
+
- Subtraction:
-
- Multiplication:
*
- Division:
/
- Remainder (modulo):
%
To round numbers in JavaScript, you can use the Math.round()
method, which rounds a number to the nearest integer:
Code For Math.round() Method In JS
let num = 4.6;
let result = Math.round(num);
console.log(result);
Output
5
You can also use the Math.floor()
method to round a number down to the nearest integer:
Code For Math.floor() Method In JS
let num = 4.6;
let result = Math.floor(num);
console.log(result);
Output
4
And the Math.ceil()
method to round a number up to the nearest integer:
Code For Math.ceil() Method In JS
let num = 4.1;
let result = Math.ceil(num);
console.log(result);
Output
5
For more specific rounding, you can use the .toFixed()
method on a number. This method returns a string representation of the number rounded to a specified number of decimal places:
Code For toFixed() Method In JS
let num = 4.666666;
let result = num.toFixed(2);
console.log(result);
Output
“4.67”
You can learn more about them in the official documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math
Conclusion
If you liked this post Math And Rounding In JavaScript, then please share this with your friends and make sure to bookmark this website for more awesome content.