Home >Web Front-end >Front-end Q&A >How to round in javascript without decimals

How to round in javascript without decimals

青灯夜游
青灯夜游Original
2022-03-28 14:50:584648browse

Method: 1. Use the "parseInt(numeric)" statement to round; 2. Use the "numeric.toFixed(0)" statement to round; 3. Use the "Math.ceil(numeric)" statement to round ; 4. Use the "Math.floor (numeric value)" statement to round; 5. Use the "Math.round (numeric value)" statement to round to an integer, etc.

How to round in javascript without decimals

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

In JavaScript, if a value does not have decimals (remove the decimal part), it can be rounded. Let me introduce to you some JavaScript rounding methods.

How to round in javascript (no decimals)

##1. parseInt()

// js内置函数,注意接受参数是string,所以调用该方法时存在类型转换
parseInt(1.5555) // => 1

2. Number.toFixed(0)

// 注意toFixed返回的字符串,若想获得整数还需要做类型转换
1.5555.toFixed(0)  // => "1"

3. Math.ceil()

// 向上取整
Math.ceil(1.5555) // => 2

4. Math. floor()

// 向下取整
Math.floor(1.5555) // => 1

5. Math.round()

// 四舍五入取整
Math.round(1.5555) // => 2

Math.round(1.4999) // => 1

6. Math.trunc()

// 舍弃小数取整
Math.trunc(1.5555) // => 1

7. Double bitwise operation and non-rounding

// 利用位运算取整,仅支持32位有符号整型数,小数位会舍弃,下同
~~1.5555 // => 1

8. Bitwise operation or rounding

1.5555 | 0  // => 1

9. Bitwise XOR rounding

1.5555^0  // => 1
[Related recommendations:

javascript video tutorial, web front-end]

The above is the detailed content of How to round in javascript without decimals. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn