Replace point by comma in Javascript

Asked

Viewed 1,539 times

4

Good night

in the example below add up if the values of 3 text boxes, and the result comes out in the fourth, how to make this result appear with comma and not with dot?

<html>
<head>
<script type="text/javascript">
function id( el ){
        return document.getElementById( el );
}
function getMoney( el ){
        var money = id( el ).value.replace(/[^0-9]/g,'');
        return parseFloat( money );
}
function soma()
{
        var total = getMoney('campo1')+getMoney('campo2')+getMoney('campo3');
        id('campo4').value = 'R$ '+total/100;
}
</script>
</head>
<body>
        <form action="" method="">
                <input name="campo1" id="campo1" value="25,60" /><br />
                <input name="campo2" id="campo2" value="5,15" /><br />
                <input name="campo3" id="campo3" value="2,63" /><br />
                <input name="campo4" readonly="readonly" id="campo4" /><br />
                <input type="button" onclick="soma()" value="Soma de Valores" />
        </form>
</body>
</html>

  • 1

    There’s another question and his excellent answers regarding how to treat money in JS, take a look there. The simple/minimalist answer to your question would be id('campo4').value = 'R$ ' + (total/100).toString().replace('.', ',');.

  • 1

    Vitor, I think that that answer is simpler for your doubt. But advice see the one that @Sergio tagged as duplicate, is much more complete.

  • cool, but where do I find this answer?

  • @Vitormarqueslourenço I gave you the answer in the first comment. And if you read the other question and answer you will know how to answer in even more detail.

1 answer

6


With the toLocaleString() Javascript can have this adapted depending on the locale:

22.33.toLocaleString(); /* depende do locale */
"22,33"

Or use a default, for example:

22.33.toLocaleString('EN');
"22.33"
22.33.toLocaleString('PT');
"22,33"

Browser other questions tagged

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