I would like to round to two decimal places, only when necessary . Here are examples of inputs and outputs
Entry:
10
1.7777777
9.1
Departure:
10
1.78
9.1
How can I do this in JavaScript?
Fragment
var valor = [
10,
1.77777777,
9.1
];
var resultado = valor.map(Math.round);
console.log(resultado);
Question inspired by Round to at most 2 decimal places
You can also use the toFixed() method , although it converts the number to a string and you would have to use the Number() function :
The downside is that it leaves 0 if the number does not contain a decimal or is less than the parameter passed to toFixed(). This little function eliminates that problem:
These two functions comply with all the tests carried out.
1. Adapted from MDN ( recommended solution )
Taking the code from Decimal Rounding , I adapted the solution so that it performs symmetric arithmetic rounding with negative numbers. That is, round -1.5 ≈ -2.
2. Using Intl.NumberFormat()
The function
Intl.NumberFormat([locales[, options]])
allows a number to be rounded correctly with native code. However, as will be seen later, this function accepts language-sensitive options, making it significantly slower.Returns a string with the representation of the number, rounded to the maximum number of decimals established. If you want to reconvert to a number, apply
parseFloat()
to the result.Discussion
When manipulating numbers by performing floating point operations , there is a limitation to accurately representing them. JavaScript uses a 64-bit floating point representation, with the associated limitations. For more information, read Why can't my programs do arithmetic correctly? .
This implies that there are numbers for which their representation presents problems to round correctly . However, the methods used in this answer solve those problems.
Also, there is another peculiar behavior that is being avoided: Math.round() rounds a 5 in the first non-significant position of a negative towards 0 .
In the following test, the rounding of negative numbers has been corrected for
Math.round()
and the cases in which each can fail are compared.Results of each answer:
However, efficiency has its trade-off in performance (see benchmark ).
In conclusion:
Math.round()
is the fastest, but it fails with negative values and has precision issues with floating point.mathRound2()
(in this same answer) extended it to the general case and resolved the error with negative values. It's still faster than the rest, but it still doesn't resolve the accuracy bug .Intl.NumberFormat()
in this answer returns the correct result in all cases, but is significantly slower than the others.round()
decimal rounding is the one that, passing all the tests, performs best . It's significantly slower thanmathRound2()
, but still achieves 50k operations per second, which is more than acceptable for many scenarios, so it's recommended for the general case where you want an accurate answer without rounding errors.Short answer
Uses
Math.round(valor * 100) / 100
Explanation
This answer is included as a popular solution, however it introduces a rounding error which may or may not be relevant. To go deeper into this see Math.round()
Fragment
Response inspired by response to Round to at most 2 decimal places
To solve this, what I thought of was to transform the number into a string, and after having processed it, convert it back to a number. The process is about splitting the number just when the dot appears. I also consider that the letter can come
e
, which marks powers of 10. If it existse-
, it is such a small number that it becomes 0, but it existse+
, it leaves it the same as the number entered.e+
If neither existse-
, finds the dot, breaks the text at a position that is the sum of the dot place and the number of decimals. It also leaves extra space, which will be decisive in approximating the number. That last character, if it is equal to or greater than 5, increases by 1, the penultimate decimal.Sometimes what is entered has few decimal places, and we want to approximate with more decimal places than that, but it is not a problem, since we can pad the number with zeros to the right, and continue processing normally.
Code:
There are many ways to round a number as well as various forms of rounding. Classical rounding (increasing one unit when the fractional part is >= 5), can be done using
Math.round
or if only the fractional part is rounded, you can usetoFixed
.Example
Simple, straightforward, beautiful and precise.
Please take a look at this simple example and check if it is what you need.
You just multiply by 100, do a Math.round and divide by 100