Hướng dẫn javascript not round number
Dogbert's answer is good, but if your code might have to deal with negative numbers, Show E.g. Use a helper function like this one instead to get consistent results:
Here's a more convenient version of this function:
If that isn't desired behaviour, insert a call to
EDIT: shendz correctly points out that using
this solution with This solution should be 100% accurate, but it will also be slower:
For those who need speed but also want to avoid floating-point errors, try something like BigDecimal.js. You can find other javascript BigDecimal libraries in this SO question: "Is there a good Javascript BigDecimal library?" and here's a good blog post about math libraries for Javascript In general, decimal rounding is done by scaling: Nội dung chính
Naive implementation Using the following function with halfway numbers, you will get either the upper rounded value as expected, or the lower rounded value sometimes depending on the input. This
In order to determine whether a rounding operation involves a midpoint value, the Round function multiplies the original value to be rounded by 10 ** n, where n is the desired number of fractional
digits in the return value, and then determines whether the remaining fractional portion of the value is greater than or equal to .5. This In the previous example, Better implementations Exponential notation By converting the number to a string in the exponential notation, positive numbers are rounded as expected. But, be aware that negative numbers round differently than positive numbers. In fact, it performs what is
basically equivalent to "round half up" as the rule, you will see that
If you want the usual behavior when rounding negative numbers, you would need to convert negative numbers to positive before calling Math.round(), and then convert them back to negative numbers before returning.
Approximate rounding To correct the rounding
problem shown in the previous
Number.EPSILON There is a different purely mathematical technique to perform round-to-nearest (using "round half away from zero"), in which epsilon correction is applied before calling the rounding function. Simply,
we add the smallest possible float value (= 1.0 ulp; unit in the last place) to the product before rounding. This moves to the next representable float value, away from zero, thus it will offset the binary round-off error that may occur during the multiplication by
After adding 1 ulp, the value of 5.015 * 100 which is Note that the size of a unit in last place ("ulp") is determined by (1) the magnitude of the number and (2) the relative machine epsilon (2^-52). Ulps are relatively larger at numbers with bigger magnitudes than they are at numbers with smaller magnitudes. Double rounding Here, we use the toPrecision() method to strip the floating-point round-off errors in the intermediate calculations. Simply, we round to 15 significant figures to strip the round-off error at the 16th significant digit. This technique to preround the result to significant digits is also used by PHP 7 round function. The value of 5.015 * 100 which is
Arbitrary-precision JavaScript library - decimal.js
Solution 1: string in exponential notation Inspired by the solution provided by KFish here: https://stackoverflow.com/a/55521592/4208440 A simple drop in solution that provides accurate decimal rounding, flooring, and ceiling to a specific number of decimal places without adding a whole library. It treats floats more like decimals by fixing the binary rounding issues to avoid unexpected results: for example, floor((0.1+0.7)*10) will return the expected result 8. Numbers are rounded to a specific number of fractional digits. Specifying a negative precision will round to any number of places to the left of the decimal point.
Solution 2: purely mathematical (Number.EPSILON) This solution avoids any string conversion / manipulation of any kind for performance reasons.
Solution 3: double rounding This solution uses the toPrecision() method to strip the floating-point round-off errors.
Solution 4: double rounding v2 This solution is just like Solution 3, however
it uses a custom
Benchmarkshttp://jsbench.github.io/#31ec3a8b3d22bd840f8e6822e681a3ac Here is a benchmark comparing the operations per second in the solutions above on Chrome 85.0.4183.83. Obviously all browsers differ, so your mileage may vary. (Note: More is better)Thanks @Mike for adding a screenshot of the benchmark. How do I round to a specific decimal in JavaScript?JavaScript Number toFixed() The toFixed() method converts a number to a string. The toFixed() method rounds the string to a specified number of decimals. How do you round a number to 2 decimal places in JavaScript?Use the toFixed() method to round a number to 2 decimal places, e.g. const result = num. toFixed(2) . The toFixed method will round and format the number to 2 decimal places. How do you control decimal places in JavaScript?To limit decimal places in JavaScript, use the toFixed() method by specifying the number of decimal places.. Rounds the number.. Converts it into a string.. Returns the number as a string.. |