3
I’m making a list of exercises about Java Script and the question where you ask
05) Dealing with numbers in Javascript can give you a lot of headache.
Have you seen what happens when you do the following command on the console:console.log(0.1 + 0.2);
The result will be:0.30000000000000004
.
Another important thing to note is the fact that the point is used in place of the comma and vice versa.
With this, we will do a simple exercise to show money always in the right way. Develop a Javascript function for it to receive a value like 0.30000000000000004 e
returnR$0,30
(note the comma and the dot)."
I got an intuitive solution that solved what was:
function reais(valorQuebrado){
return `R$:${Math.floor(valorQuebrado)},${Math.floor(100 * valorQuebrado)}`
}
console.log(reais(0.30000000000000004))
console.log(reais(0.2 + 0.1))
However, the solution of the exercises gave me another type of solution that was:
function formatarValorDecimal(valorDecimal) {
valorEmReais = `R$ ${valorDecimal.toFixed(2).toString().replace(".", ",")}`
console.log(valorEmReais)
}
formatarValorDecimal(0.1 + 0.2)
I would like to know if there is a difference between the answers, or if my answer does not reach the general cases, so it could be a future code error.
There are cases that give difference yes, because of rounding (and the first does not guarantee only two decimal places), see: https://ideone.com/SXz4LT <-- here also has another alternative, with
toLocaleString
. Also interesting to read: https://answall.com/q/11018/112052– hkotsubo