0
Hello, I have a small problem, I have a number coming from a sum and I need to assign a mask to that number. I did some tests until it worked however the mask was not correct to the number.
var format = function (format, text) {
var array = text.split("");
return format.replace(/{(.*?)}/g, function (index) {
return array.splice(0, index.replace(/\D/g, "")).join("");
});
};
var texto = format("{3}.{3}.{3}.{3},{2}", trasfN);
document.getElementById('calTotal').value = texto;
alert(texto);
In a test the number is returning me that 162.312.0.
and the correct thing would be to return 16.231,20*
Wouldn’t it be a case of using the
toLocaleString
so https://answall.com/a/147086/129 ?– Sergio
I tried to implement, but I did not see another example using toLocaleString, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString
– Fernando
var trasfN = parseFloat(Math.round(calTotal * 100) / 100). toFixed(2). toLocaleString('de-de');
– Fernando
var trasfN = parseFloat(Math.round(calTotal * 100) / 100). toFixed(2). replace("." , ""). toLocaleString('de-de');
– Fernando
I tried these two ways, but there was no difference
– Fernando
The localeString is for numbers, don’t do
toFixed
... Forehead like this:– Sergio
https://jsfiddle.net/Sergio_fiddle/2o6nb1hm/
– Sergio
I passed this way: var trasfN = parseFloat(Math.round(calTotal * 100) / 100). toLocaleString('pt-BR', {maximumFractionDigits: 2});
– Fernando
It even worked, but it did not return 0 the right, returned this way: 16.231,2
– Fernando
Okay, and did you do what you wanted? If you use the
Math.round
you’ll never get decimal part.– Sergio
was using toFixed to return that 0 and display the 1623120
– Fernando
Okay, use
maximumFractionDigits
andminimumFractionDigits
. So you fix the number.– Sergio
Forehead like this
(1623120).toLocaleString('pt-BR', {
 maximumFractionDigits: 2, minimumFractionDigits: 2
});
will give1.623.120,00
– Sergio
keeps returning only one home after the comma
– Fernando
var trasfN = parseFloat(Math.round(calTotal * 100) / 100). toLocaleString('en-BR', {maximumFractionDigits: 3});
– Fernando
Did you see my last comment here? You tested?
– Sergio
The complete number coming from the sum would be this: 16231.199999999999, and I deal with parseFloat(Math.round(calTotal * 100) / 100) to round and the . toFixed(2) I only came the last 2 numbers after the comma
– Fernando
I saw yes and the result was the same only 1 number after the comma
– Fernando
Take a look here: https://jsfiddle.net/Sergio_fiddle/2o6nb1hm/1/ is this? And what I had already explained in the comments here. You have to use both o
minimumFractionDigits
and themaximumFractionDigits
to be neither more nor less than 2 decimal places.– Sergio
Thank you very much!
– Fernando