Include a point and comma to a variable

Asked

Viewed 161 times

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*

  • 1

    Wouldn’t it be a case of using the toLocaleString so https://answall.com/a/147086/129 ?

  • 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

  • var trasfN = parseFloat(Math.round(calTotal * 100) / 100). toFixed(2). toLocaleString('de-de');

  • var trasfN = parseFloat(Math.round(calTotal * 100) / 100). toFixed(2). replace("." , ""). toLocaleString('de-de');

  • I tried these two ways, but there was no difference

  • The localeString is for numbers, don’t do toFixed... Forehead like this:

  • https://jsfiddle.net/Sergio_fiddle/2o6nb1hm/

  • I passed this way: var trasfN = parseFloat(Math.round(calTotal * 100) / 100). toLocaleString('pt-BR', {maximumFractionDigits: 2});

  • It even worked, but it did not return 0 the right, returned this way: 16.231,2

  • Okay, and did you do what you wanted? If you use the Math.round you’ll never get decimal part.

  • was using toFixed to return that 0 and display the 1623120

  • Okay, use maximumFractionDigits and minimumFractionDigits. So you fix the number.

  • Forehead like this (1623120).toLocaleString('pt-BR', {
 maximumFractionDigits: 2, minimumFractionDigits: 2
}); will give 1.623.120,00

  • keeps returning only one home after the comma

  • var trasfN = parseFloat(Math.round(calTotal * 100) / 100). toLocaleString('en-BR', {maximumFractionDigits: 3});

  • Did you see my last comment here? You tested?

  • 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

  • I saw yes and the result was the same only 1 number after the comma

  • 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 the maximumFractionDigits to be neither more nor less than 2 decimal places.

  • Thank you very much!

Show 15 more comments
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.