Home Common Problem js rounding

js rounding

Jul 04, 2023 am 10:07 AM
javascript rounding

JS rounding methods: 1. tofixed method, which can round Number to a number with specified decimal places; 2. round() method, which can round a number to the nearest integer.

js rounding

1. tofixed method

toFixed() method can round Number to a number with specified decimal places. For example, if the data Num is kept to 2 decimal places, it is expressed as: toFixed(Num); however, the rounding rules are different from those in mathematics. The banker's rounding rule is used. Banker's rounding: the so-called banker's rounding method , its essence is a method of rounding up to five to get even (also known as rounding up to five and leaving even). The specific rules are as follows:

To put it simply: consider rounding up to five. If the number after five is not zero, add one. If the number after five is zero, look at the odd or even number. If the number before five is even, it should be discarded. If the number before five is odd, it should be discarded. Further.

Obviously this rule does not conform to the way we usually deal with data. In order to solve this problem, you can customize the implementation using the Math.round method to specify how many bits of data to retain for processing.

2, round method

round() method can round a number to the nearest integer. For example: Math.round(x) takes x to the nearest integer. The rounding method is used in the rounding method, which conforms to the rules of rounding in mathematics. The processing of decimals is not so convenient, but it can be customized according to different requirements.

For example: to process X with two decimal places, you can use Math.round(X * 100) / 100 for processing.

Other content:

In JavaScript, the scenarios for rounding values ​​are as follows:

Round up: ceil round down: floor rounding: round fixed precision: toFixed fixed length: toPrecision rounding: parseInt, bit operation

This article will briefly explain and summarize these 6 APIs.

1. Round up: ceil

ceil means `ceiling`, which means the integer above a value and closest to the number. ceil is a static method of the Math object and needs to pass a parameter. Its calling method is as follows:

Math.ceil(12.34); //13Math.ceil(12.68); //13

2. Round down: floor

floor means `floor`, which means the nearest integer under a value. floor is a static method of the Math object and needs to pass a parameter. The calling method is as follows:

Math.floor(12.34); // 12Math.floor(12.68); // 12

3. Rounding: The function of round

round is to round a floating point number and retain the integer digits. round is also a static method of the Math object and also needs to pass a parameter. Its calling method is as follows:

Math.round(12.34); // 12Math.round(12.54); // 13

4. Fixed precision: toFixed

toFixed is different from the above three methods. It is a method implemented on the Number prototype. Its function is to round a floating point number and retain fixed decimal places. toFixed needs to pass a parameter, and its calling method is as follows:

100.456001.toFixed(2); // 100.46100.456001.toFixed(3); // 100.456

5, fixed Length: toPrecision

toPrecison is also a method implemented on the Number prototype to process floating-point numbers. The difference from toFixed is that it rounds a floating-point number and retains a fixed length of significant digits, including the integer part.

99.456001.toPrecision(5); // 99.456100.456001.toPrecision(5); // 100.46

6. Rounding: parseInt

parseInt Yes A method on the global object window, its function is to round a convertible value, which is divided into the following two situations:

1. Convert the string value into a Number integer, and round each value in the string Characters are converted until an unconvertible character (including a decimal point) is encountered.

2. Round floating point type values, ignore the decimal part, and do not round

// String value parseInt('100'); // 100parseInt('100axt') ; // 100parseInt('100xh20'); // 100parseInt('100.78'); // 123// Number type parseInt(100.12); // 100parseInt(100.78); // 100

7. Rounding: Bit operations

| 0: Perform a bitwise OR operation with 0, the original value remains unchanged~~: The original value obtained by two bitwise NOT operations is also the original value>> 0: Right shift 0 bits<< 0: Left shift 0 bits>>> 0: Unsigned right shift 0 bits

These bit operators will show some common characteristics when implementing rounding operations. :

For the Number type, applying bit operations directly will result in almost the same result as parseInt; for other types, it will be converted to a numeric value internally through Number(), and then bit operations will be applied. When bit operations are applied to the special NaN and Infinity values, both values ​​are treated as 0.

For Number type, bit operations are applied directly.

~~ 100.12; // 100100.78 | 0; // 100100.45 >> 0; // 100100.50 << 0; // 100100.96 >>> 0; // 100

For other types, first use Number() to convert to numeric type, and then perform bit operations.

~~ '100.12' // 100, Number('100.12') == 100.12'100.50' >> 0; // 100, Number('100.50') == 100.50'100.96' < ;< 0; // 100, Number('100.96') == 100.96~~ 'abc' // 0, Number('abc') == NaN'12abc' >> 0; // 0, Number ('12abc') == NaNundefined | 0 ; // 0, Number(undefined) == NaN~~null; // 0 , Number(null) == 0true >> 0; // 1 , Number(true ) == 1false >> 0; //0 , Number(false) == 0[] << 0; // 0 , Number([]) == 0~~NaN; // 0 Infinity > ;>> 0; // 0

Bit operations operate at the most basic level, that is, operating on values ​​based on the bits in memory that represent the value.

The reason why bit operations can be rounded is:

The values ​​in ECMAScript are stored as 64-bit double-precision floating point numbers, but bit operations can only be applied to integers, so the 64-bit floating point numbers must be converted first. The point number is converted into a 32-bit integer, and then bit operations are performed, and finally the calculation result is converted into a 64-bit floating point number for storage.

The above is the detailed content of js rounding. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

PHP floating point number rounding method PHP floating point number rounding method Mar 21, 2024 am 09:21 AM

This article will explain in detail the PHP floating point number rounding method. The editor thinks it is very practical, so I share it with you as a reference. I hope you can gain something after reading this article. PHP Floating Point Rounding Overview Floating point numbers are represented in computers as a decimal point followed by an exponent, however, they are often stored in approximations with a limited number of digits. When you need to round a floating point number to a specific precision, there are several ways to do it. Method 1. round() function The round() function rounds a floating point number to the nearest integer. It accepts floating point numbers and optional precision parameters. For example: $num=1.55;echoround($num);//Output: 2echoround($num,1)

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).