JavaScript four numerical rounding methods

Source: Internet
Author: User

One, Math.trunc () 1. Definition

The Math.trunc () method removes the fractional part of a number, preserving the integer portion.

2. Syntax
Math.trunc(value)
3. Example
console.log(Math.trunc(2.01)); // 2console.log(Math.trunc(2.9)); // 2console.log(Math.trunc('0.22')); // 0console.log(Math.trunc(-1.22)); // -1console.log(Math.trunc(-1.56)); // -1console.log(Math.trunc(true)); // 1console.log(Math.trunc(undefined)); // NaN
II, Math.Round () 1. Definition

The Math.Round () method returns the integer part after a number is rounded.

2. Syntax
Math.round(value)
3. Example
console.log(Math.round(2.01)); // 2console.log(Math.round(2.9)); // 3console.log(Math.round('0.22')); // 0console.log(Math.round(-1.22)); // -1console.log(Math.round(-1.56)); // -2console.log(Math.round(true)); // 1console.log(Math.round(undefined)); // NaN
Iii. Math.ceil () 1. Definition

The Math.ceil () method returns the smallest integer greater than or equal to the number, which is rounding up.

2. Syntax
Math.ceil(value)
3. Example
console.log(Math.ceil(2.01)); // 3console.log(Math.ceil(2.9)); // 3console.log(Math.ceil('0.22')); // 1console.log(Math.ceil(-1.22)); // -1console.log(Math.ceil(-1.56)); // -1console.log(Math.ceil(true)); // 1console.log(Math.ceil(undefined)); // NaN
Iv. Math.floor () 1. Definition

The Math.floor () method returns a minimum integer less than or equal to a number, which is rounded down.

2. Syntax
Math.floor(value)
3. Example
console.log(Math.floor(2.01)); // 2console.log(Math.floor(2.9)); // 2console.log(Math.floor('0.22')); // 0console.log(Math.floor(-1.22)); // -2console.log(Math.floor(-1.56)); // -2console.log(Math.floor(true)); // 1console.log(Math.floor(undefined)); // NaN

JavaScript four numerical rounding methods

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.