how to represent a monetary field with semicolons in javascript jquery

Asked

Viewed 4,210 times

10

I’m having a huge doubt.

I need to take the values that are in the database with decimals of 3 (for example: 56826.497) and show on the screen the value 56.826,497. I’ve tried using the maskMoney and the priceformat, but they didn’t work out.

The maskMoney even serves to insert the values correctly, forcing me to insert only numbers and the way I format (56,826,497). However, when it loads the value of the database to view on the screen, it appears as 56826,497. detail: I am loading the values like this:

In HTML I am 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>
  • thank you very much. helped a lot

  • Possible duplicate: http://answall.com/questions/11018/howto represent money

2 answers

5

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

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

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

Using the 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.: Try changing the formatter to $ 0,0.00 and see how no rounding error is introduced.

PS2.: Another great advantage of using the numeral.js is that naturally your system is already born ready to internationalisation (i18n)

  • could you show me how to apply this plugin in the formatting of a column of [link] https://datatables.net [/link] ? , example: "aoColumns": [ { "sName": "ValorUnitario", "mData": "ValorUnitario", "sWidth": "10%" },.

  • 1

    @Adrianosuv you will use the method { render: function(numeroSemFormatacao) { return formatar(numeroSemFormatacao); } }

2

There are some ways to turn this into currency.

External plugin

You can use the Google Code plugin, formatcurrency to do this, download it here: https://code.google.com/p/jquery-formatcurrency/

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 of this topic)

  • Defining total=56826.497 Your code works for me "56,826.50" what would be "incorrect" for this question, that is, out of the correct format of thousand(dots) and comma, of which is in the title of the question, and also in the content of the question you can read "e mostrar na tela o valor 56.826,497" and note that its result is reversed.

  • You just reverse the dot with the comma in the regex

  • But what I’m saying is that for this to be an answer valid you should have done it by now, you know?

  • I understand, but the answers are intended to help as much as possible, the rest of the user will be able to interpret the code and incorporate it in your application. I believe this answer is valid, because your problem has been solved, display details and details can be adjusted within your application. Anyway I will edit for other users search reasons too.

  • 1

    Use toFixed with money is snare! There are well known rounding problems with toFixed. And another detail, parseFloat only takes one parameter. Radix is only for parseInt. I suggest a library like the bigmoney.js if you intend to make any financial calculation. In addition it has a functionality of Formatacao that can be useful

  • 1

    Another library that may be useful is the js numeral.

  • thank you very much. helped a lot

Show 2 more comments

Browser other questions tagged

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