how to represent a monetary field with semicolons in javascript jquery

10

I have a huge doubt.

I need to get the values that are in the database with decimal places of 3 (for example: 56826.497) and display 56,826,497 on the screen. I already tried using maskMoney and priceformat , but they did not work.

maskMoney even serves to insert values correctly, forcing me to only enter numbers and the way I format (56,826,497). However, at the time it loads the value of the database to display on the screen, it appears as 56826.497. detail: I'm loading the values like this:

In HTML I'm using the code below:

//----------------------------------------------------------------- no cabeçalho
* <script src="../scripts/js/jquery.maskMoney.min.js"></script>
//------------------------------------------------------------------ no cabeçalho
* <script>
$(function(){
   $('#commod_com_imp, #serv_com_imp, #commod_sem_imp, #serv_sem_imp').maskMoney({ thousands: '.', decimal: ',' });
            });
//------------------------------------------------------------------ no momento de carregar a página

function preenche_primeira_vez() { // Preenchimento na primeira vez  
    indice_bd=0;
    get_num_registros();
    $("input").prop('disabled',true); // Colocando todos os campos como desabilitado
    $("select").prop('disabled',true); // Colocando todos os campos como desabilitado
    $.ajax({
        type: "GET",
        url: "../funcoes.php",
        data:{acao:"consulta_preco", offset:indice_bd, numlinhas:1, nome_tabela:'cliente,preco'},
            success:function(resp_consulta) {
                consulta_formatada = $.parseJSON(resp_consulta);
                $("input[name=commodity_com_imp]").val(consulta_formatada[0].commodity_com_imp.replace("." , ","));

//------------------------------------------------------------------ no body
<div class="texto_e_valor_com_3">
<div class="texto">Preço commodity com imposto (R$/m<sup>3</sup>)</div>
<div class="valor"><input type="text" MAXLENGTH="10" name="commodity_com_imp" id="commod_com_imp"/></div>
    
asked by anonymous 08.12.2014 / 12:06

2 answers

4

JavaScript has rounding problems, so any solution that includes the .toFixed function is not a good option. I recommend using already tested libraries.

I I like to use two libraries together, which give me total flexibility to solve this kind of problem; For calculations I use bigmoney.js and for formatting I use numeral.js .

In your case you would only need numeral.js and the plugin you already use to collect user data, within the specific formatting of your system.

Using numeral.js your code looks like this;

(function () {
    // Esse código é para configurar para pt-br, afinal não tem como o numeral.js
    // "descobrir do nada" qual formatação você quer
    var language = {
        delimiters: {
            thousands: '.',
            decimal: ','
        },
        abbreviations: {
            thousand: 'mil',
            million: 'milhões',
            billion: 'b',
            trillion: 't'
        },
        ordinal: function (number) {
            return 'º';
        },
        currency: {
            symbol: 'R$'
        }
    };

    // Node
    if (typeof module !== 'undefined' && module.exports) {
        module.exports = language;
    }
    // Browser
    if (typeof window !== 'undefined' && this.numeral && this.numeral.language) {
        this.numeral.language('pt-br', language);
    }
}());

numeral.language('pt-br');

var valor = new numeral(859.385).format('$ 0,0.000'); //Esse é o código que você precisa
document.write(valor);
<script src="http://cdnjs.cloudflare.com/ajax/libs/numeral.js/1.4.5/numeral.min.js"></script>

PS.:Trychangingtheformatterto$0,0.00andseehownoroundingerrorisintroduced.

PS2.:Anothergreatadvantageofusingnumeral.jsisthatofcourseyoursystemisalreadybornreadyfor#

    
08.12.2014 / 15:34
2

There are a few ways to turn that into currency.

External plugin

You can use the Google Code plugin, formatcurrency to do this, download it here: link

By code

Another way is to use regex or else JS code to do.

Via jQuery:

$(".totalSum").text('$' + parseFloat(total, 10).toFixed(2).replace(/(\d)(?=(\d{3})+\,)/g, "$1.").toString());

(You can check the answers for this topic )

    
08.12.2014 / 12:51