Code

Rounding Numbers in JS: Math round, floor, ceil, and trunc

Rounding Numbers in JS: Math round, floor, ceil, and trunc / Skillbox Media

Educational program with employment guarantee: "Frontend Development and Artificial Intelligence"

Find out more

Rounding numbers is one of the fundamental operations in programming. At first glance, this task may seem simple. However, in practice, various questions often arise: which method should be used, how negative values ​​are handled, and how to avoid rounding errors to a given number of decimal places.

Contents

  • Numbers in JavaScript have a number of unique characteristics. First, the programming language uses the IEEE 754 standard for representing double-precision floating-point numbers, which allows working with numbers in the range from approximately 5.0E-324 to 1.7976931348623157E+308. This provides significant accuracy, but it is worth noting that not all decimal fractions can be represented exactly, which can lead to unexpected results in calculations.

    Furthermore, JavaScript does not support different numeric types, unlike many other languages. All numbers, including integers and fractions, are treated as floating-point numbers. This means that while you can use integers, they will be stored in the same format as fractional numbers.

    Developers should also be careful about rounding and precision issues. For example, operations with numbers can introduce rounding errors. Therefore, it is recommended to use methods for precise calculations, such as Math.round(), Math.ceil(), or Math.floor(), to avoid unwanted situations.

    JavaScript provides the ability to work with large numbers using the BigInt type, which allows you to store integers of arbitrary length. This is especially useful for tasks involving large calculations or when working with cryptography.

    In conclusion, understanding the nature of numbers in JavaScript is an important aspect for developers, as it will help avoid common mistakes and ensure more accurate calculations in applications.

  • The Math object in JavaScript is a built-in object that provides a variety of mathematical functions and constants. It does not require instantiation; instead, functions and properties are available directly through the object itself. Math provides tools such as methods for performing arithmetic operations, calculating trigonometric values, and constants such as pi. This object simplifies complex mathematical calculations, making them more accessible to developers.
  • Math.floor() is a function that rounds a number down.
  • Math.ceil() is a function designed to round a number up to the nearest integer.
  • Math.round() is a function that rounds numbers according to generally accepted mathematical rules.
  • Math.trunc() is a function designed to remove the decimal part of a number.
  • The rounding functions can use various types of arguments. Typically, these are numeric values ​​that need to be rounded to a specified number of decimal places. In addition, arguments can be references to cells containing numeric data. It is also permissible to use expressions that return numeric results, which allows you to dynamically calculate the value to be rounded. In some cases, functions may accept additional parameters that determine rounding rules, such as the direction of rounding (up or down).
  • To round a number to a specific number of decimal places, follow these simple steps. First, determine exactly how many decimal places you want to keep. Then, look at the digit immediately after the last digit you want to keep. If this digit is 5 or greater, add 1 to the last digit you want to keep. Otherwise, leave the last digit unchanged. Then, remove all digits to the right of the desired number. This will give you the rounded value.
  • Problems that use rounding techniques can be varied and occur in a variety of fields. For example, in the financial sector, rounding is often required when calculating taxes or interest rates to simplify data processing and avoid complex fractions.

    In mathematics, rounding can be used when performing calculations to make tasks that require quick solutions easier, such as when evaluating results or when rounding off long numbers.

    In statistics, when data needs to be presented in a more visual form, survey or measurement results are often rounded to make the information more accessible and easier to understand.

    Furthermore, in engineering, rounding can be useful in design, where precise dimensions of parts can be adapted for convenience and ease of manufacture.

    Educational settings, such as mathematics classes, also make extensive use of rounding problems to help students develop their number skills.

    Thus, rounding techniques find application in a wide variety of fields, from finance to education, helping to simplify and improve data processing processes.

  • Common Rounding Mistakes

In JavaScript, rounding of numbers is accomplished using the Math object, which includes methods such as Math.floor, Math.ceil, Math.round, and Math.trunc.

Besides those mentioned, the Math object also offers many other useful functions that are often used in conjunction with rounding. For example, Math.abs(x) calculates the absolute value of a number, Math.random() generates a random number between 0 and 1, Math.pow(x, y) raises x to the y power, and Math.sqrt(x) returns the square root of a number. You can learn more about these and other methods in the documentation.

In this article, we'll look at how rounding works in JavaScript, discuss its nuances, and share practical recommendations for using this knowledge.

First, let's discuss how numbers work in JavaScript.

Unique Characteristics of Numbers in JavaScript

JavaScript distinguishes between two main types of numbers. The main ones are standard integers and fractional values. They are capable of representing a range from approximately minus 9 quadrillion to plus 9 quadrillion, or more precisely, from −(2⁵³ − 1) to 2⁵³ − 1. These numbers are classified under the number type.

JavaScript uses a standard known as "double-precision floating-point numbers" to store numbers. The essence of this approach is that numbers are represented in the binary system. The problem occurs not with integers, but with certain decimal fractions that cannot be precisely encoded in binary. This is similar to the situation in the decimal system, where 1/3 cannot be expressed precisely and becomes 0.333…

Thus, unusual situations may sometimes be observed during operations:

This is not a bug inherent to JavaScript - numbers are stored in a similar way in any programming language that uses this format. To minimize the likelihood of errors, it is necessary to round the result:

First, multiply the total by 100 to remove the decimal point, then round and divide the resulting value back.

The second type of numbers is quite rare - these are very large or very small values ​​that fall outside the standard range of numbers (exceeding 2⁵³ − 1 or below −(2⁵³ − 1)). This format is designated as BigInt. Such numbers do not allow fractional values; they can only be integers. The representation of such numbers looks like this:

Keep in mind that the letter n at the end of the number is a signal to JavaScript that this value belongs to the BigInt type.

In practice, BigInt is rarely used, and its role is mainly in the field of cryptography. However, in this article, we will not go into detail on this topic, but will focus on rounding issues.

Understanding the Math Object in JavaScript

Math is a built-in object that makes it easy to manipulate numbers. It can perform rounding operations, calculate roots, generate random numbers, and perform many other functions.

Unlike many other objects in JavaScript, Math is not intended to be used as a function or instantiated. For example, attempting to call new Math() will result in an error.

The Math object is interacted with exclusively through its methods and properties, which are predefined commands. Here's an example of how this is implemented:

In this article, we'll focus exclusively on Math's ability to round numbers.

Math.floor() Function: The Principle of Rounding Down

The Math.floor() function rounds a number down to the nearest integer less than or equal to the original value. It simply ignores the fractional part without adding one, even if the number is very close to the next integer.

Even if the number is negative, Math.floor() will round it down, which means it's closer to the next lower value.

This approach is used to determine the number of pages or chunks in cases where fractional values ​​cannot be taken into account.

If you have 23 comments and one page can accommodate 5, you need to divide the total number of comments by the number that fits on the page. So, 23 divided by 5 equals 4 with a remainder. This means that you will be able to display 4 full pages, and the remaining comments will take up part of the fifth page.

The result is 4 pages. If we went to the fifth page, only 3 comments would remain. In this case, the Math.floor() method will return the number of pages that are completely filled.

Math.ceil() Function: How Rounding Up Works

Rounds its argument up to the nearest whole number.

Negative numbers are also rounded, in which case the process is carried out towards zero, which results in an increase in their value.

If you have 103 posts and you plan to display 20 posts on each page, then to calculate the number of pages required, you need to divide the total number of posts by the number of posts that fit on one page.

103 divided by 20 yields 5 full pages with the remainder. Since the remaining records also require a separate page, you need to add another page to display them. Therefore, you will need 6 pages to accommodate all the records.

To fit 103 records, you will need 6 pages.

Math.round() Method: Rounding According to Mathematical Standards

The Math.round() function rounds a number according to generally accepted rules, known from school.

  • If the fractional part of a number is less than 0.5, then rounding is performed downwards.
  • If the value is equal to or greater than 0.5, then it is rounded up to the nearest whole number.

For positive numbers, the result of rounding is always predictable. However, for negative values, the Math.round() function behaves differently: it rounds towards zero if the fractional part is 0.5.

If a video is 95 seconds long, to convert this value to minutes, divide the number of seconds by 60. The result is 1 minute and 35 seconds.

The final time is 2 minutes. In this case, the rounding method resulted in 1.58 being reduced to the nearest whole number. If the video were 89 seconds long, it would correspond to one minute.

Math.trunc() — removing the decimal part of a number

The Math.trunc() function does not round numbers; it simply truncates all digits after the decimal point. It stores only the whole number portion, regardless of whether it is positive or negative.

When a user uses the mouse to draw a rectangle, the coordinates they receive may be fractional. However, to display the rectangle correctly, these values ​​must be converted to whole numbers.

In our program, we use the Math.trunc() function because we only want the coordinates to be rounded down.

Suppose the program calculated a discount of -12.95. In this case, we only want to keep the whole number for the audit trail, excluding the decimal places.

This way, we remove the decimal portion without rounding, thereby preserving the overall value.

Types of Arguments for Rounding Functions

The Math.round(), Math.floor(), Math.ceil(), and Math.trunc() functions are designed to work with numeric data. However, JavaScript is flexible: if you pass a non-numeric value to these functions, either intentionally or by mistake, the engine will attempt to convert it to a number. The result of this conversion can vary—sometimes it succeeds, while others fail. If Math fails to convert the passed value to a number, the result will be NaN.

NaN, which is an abbreviation for Not-a-Number, is a unique value in JavaScript that means "not a number." This value occurs when a mathematical operation involving numbers does not produce a valid result, for example:

Let's analyze how the different types of values ​​function.

When a string contains text, the resulting value will be NaN. JavaScript first converts a string containing a number to a number format and then performs rounding.

The Boolean values ​​true and false are converted to their numeric equivalents, 1 and 0, respectively.

In JavaScript, the null value is interpreted as an "empty" or "unavailable" state. This value can be manually set for a variable that does not currently contain any data.

For rounding purposes, it is reasonable to interpret the null value as 0.

The term undefined indicates that a variable exists but does not contain any data. This value is automatically assigned when you declare a variable but do not initialize it.

In this case, the value variable is present, but it cannot be rounded, resulting in a NaN value.

If you try to round a NaN value, the result remains NaN.

It is even possible to round an array in JavaScript. This may seem unusual, but in some cases it can actually be useful.

Let's analyze three cases:

The array [5.3] is first converted to the number 5.3. Then, using the Math.ceil() function, this value is rounded up, resulting in 6.

The empty array [] is converted to zero. Therefore, the result of rounding is zero.

The last array has two elements: [1, 5]. JavaScript has a difficulty in determining which number was intended, resulting in a NaN value.

When you process user-supplied data, be sure to convert it to a number before rounding.

This will prevent unexpected behavior. The NaN value is dangerous because it can propagate through a sequence of calculations:

Methods for rounding numbers to a specific number of decimal places

The methods of the Math class do not provide a direct way to round numbers to a specific number of decimal places. If you need to round a number, for example, to two decimal places, there are several approaches, including the use of various alternative methods.

To round a number to n decimal places, you should follow these steps:

  • multiply it by 10 to the power n - this will allow us to move the decimal point.
  • apply rounding;
  • We return the result and divide it by 10 to the power n.

For example, let's round the value 1.23789 to two decimal places.

The toFixed() method allows you to round a number to a specific number of decimal places. It applies standard mathematical rules: if the next digit is 5 or higher, then rounding occurs up. It's worth noting, however, that the result of this method is a string, not a numeric value.

Rounding to two decimal places yields a value of «5.68».

If you enter zero or no data, the value will be rounded to the nearest whole number.

To return a string to a numeric format, you can use the parseFloat() function:

Illustrations of the application of rounding methods in various problems

The Math.round, Math.floor, Math.ceil, and Math.trunc methods are widely used in various problems.

Imagine that you have added an item to your cart that costs 349,999 rubles. This item comes with a discount of 12.75 rubles, but the store rounds the discount down to avoid overpayment. After the discount is applied, the total will also be rounded up to the nearest whole ruble.

Steps:

  • Apply rounding down the discount using the Math.floor function.
  • Remove the discount from the total.
  • Round the total to the nearest whole number using the Math.round function.

Imagine you are planning to design a three-column grid layout and you have the following requirements:

  • The container completely accommodated the columns.
  • The main element was perfectly positioned horizontally.

Determining the column width:

Explanation:

  • Determining the width of one of the columns:

799.8 / 3 = 266.6.

  • We reduce the values ​​to ensure that all three columns fit completely within the container:

Rounding 266.6 to the nearest whole number gives 266.

  • Let's check the answer:

266 multiplied by 3 equals 798 (everything fits).

That leaves 1.8 pixels that can be used as gutters between columns.

There is a parent container with a width of 800 pixels and an element nested within it that is 375 pixels wide. We need to determine the horizontal center position of this nested element within its parent block.

Solution:

Explanation:

  • Let's determine the left margin of the center element relative to the parent container.

(800 - 375) divided by 2 equals 212.5.

  • To avoid "blurred" edges or offsets, we need to round the resulting value to the nearest whole pixel.

Rounding 212.5 equals 213 pixels.

If your goal is to smoothly move an element, such as a circle, from left to right, keep in mind that the x coordinate is updated on every frame and can take fractional values. However, the CSS left property requires whole numbers in pixels. Using fractional values ​​may cause the browser to display the element blurrily or even create a shaking effect.

Solution:

Explanation:

  • x = 123.78 - this value is determined in a variable way, depending on factors such as timing or speed.
  • Round to the nearest whole number: Math.round(x) results in 124.
  • CSS requires precise coordinates, so element.style.left = ‘124px’ is used.

Using fractional coordinate values ​​(for example, 123.78px) may cause the element to display blurrily or even create a shaking effect when moved.

Common Rounding Mistakes

Let's Discuss Common mistakes people make when working with Math methods.

Sometimes, beginning programmers try to use the Math.round() function with two parameters.

This function does not function as expected because Math.round only accepts one value. The second parameter is simply not taken into account.

The solution is to use a single argument.

Sometimes, beginning developers believe that using rounding will help eliminate the difficulties associated with floating-point numbers.

First, it is necessary to improve accuracy.

Learn more fascinating facts about programming in our Telegram channel. Join us!

Read also:

  • JavaScript is a programming language that is widely used to create interactive elements on websites. Its main function is to add dynamics and interactivity to web pages, allowing users to interact with the content in real time. JavaScript allows developers to manipulate elements on a page, handle events such as button clicks or mouse movements, and interact with the server to load data without having to refresh the entire page.

    Furthermore, this language is an important part of modern web development, as it works in conjunction with HTML and CSS to form a triad of technologies necessary for creating modern web applications. JavaScript is also supported by all modern browsers, making it a versatile tool for developers looking to build cross-platform solutions.

  • Basic Operators in JavaScript
  • Functions in JavaScript: How to Create, Call, and Use Them Correctly