Format decimal in monetary value

Asked

Viewed 1,076 times

4

Which plugin or logic I can format values monetary returning from the bank dynamically?

  • 8
  • 3

    Although the answer is on this link, I think it would be nice to have another one here. After all the other question is much more comprehensive, and there the formatting is treated as detail (and is not even dealt with in all the answers). Here the question is specifically about formatting. Although, Al Unser Albuquerque, it would be cool if you [Dit] the question and tell how your data is in the database, and how are they getting into JS. Are they strings? Are they numbers? Floats?

2 answers

3

A practical example with 2 functions that simplify formatting in a very generic way:

<html>
<head>
<script type="text/javascript">

function number_format(number, decimals, dec_point, thousands_sep) {
    number = (number+'').replace(',', '').replace(' ', '');
    var n = !isFinite(+number) ? 0 : +number, 
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + Math.round(n * k) / k;
        };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
}
</script>
</head>
<body>

<script type="text/javascript">
document.write( number_format( 5000.000000, 2, '.', ',' ) );
document.write('<br />');
document.write( number_format( 5000.000000, 2, ',', '.' ) );
document.write('<br />');
document.write( number_format( 5000.000000 ) );
document.write('<br />');
document.write( number_format( 5000.000000 ) );
</script>

</body>
</html>

The function number_format is from the PHPJS.org project: http://phpjs.org/functions/number_format/

This project translates PHP functions to the Javascript language.

The function number_format has the same characteristics as the original in PHP: http://php.net/number_format

The parameters nomenclature is self-explanatory

number -> o número
decimals -> quantidade de casas decimais
dec_point -> caracter representativo para as casas decimais
thousands_sep -> caracter representativo para casa de milhares

Important to be aware that we are not talking about business rules.

For example, when formatting a decimal value set to be displayed without decimals, evaluate whether the business model requires rounding up or down. In such cases, it is necessary to implement with the functions ceil() or floor() or, as appropriate.

1

Well I did a function on the same hand I’ll post both cases, float for coin, and coin for float:

custom = {};

custom.convertFloatToMoeda=function(result){
    var neg=false;
        if(result == null){ return "0,00"; }

        for (i=0;i<result.length;i++){
            if (result.toString().charAt(i)==','){ return alert('erro convertFloatToMoeda =>' +result+' nao é tipo float' ); }
            if (result.toString().charAt(i)=='-'){ neg=true; }
        }

        array = result.toString().split('.');
        result = array[0];
        var ponto = result.length;

        if(neg == true){
            while( ponto > 3 ){
                ponto = ponto - 3;
                result = splice( result,ponto, 0, "." );
                result = result.replaceAll('-.','-');
            }
        }
        else{
            while( ponto > 3 ){            
                ponto = ponto - 3;
                result = splice( result,ponto, 0, "." );
            }
        }

        var tam = array.length; //tamanho do array (para ver se tem decimais)
        if(tam > 1){            //caso tenha decimais
            if(array[1].length <= 1){       //caso tenha um digito tipo 10,3 (virgula trinta)
                array[1] = array[1] + '0';
            }
            return result + ',' + array[1]; //decimais
        }
        return result+',00'; //retorna decimais zerados se nao houver decimais
};

/**
 * @param {type} String, recebe  no formato xxx.xxx,00
 * @returns {type } String formato xxx.xxx
 */
custom.convertNumero=function(result){
var neg=false;
        if(result == null){ return "0,00"; }

        for (i=0;i<result.length;i++){
            if (result.toString().charAt(i)==','){ return alert('erro convertFloatToMoeda =>' +result+' nao é tipo float' ); }
            if (result.toString().charAt(i)=='-'){ neg=true; }
        }

        array = result.toString().split('.');
        result = array[0];
        var ponto = result.length;

        if(neg == true){
            while( ponto > 3 ){
                ponto = ponto - 3;
                result = splice( result,ponto, 0, "." );
                result = result.replaceAll('-.','-');
            }
        }
        else{
            while( ponto > 3 ){            
                ponto = ponto - 3;
                result = splice( result,ponto, 0, "." );
            }
        }
        return result; 
};

Of course we could bring it already formatted in the sql query itself, in case I will demonstrate in mysql:

select format(suaColuna,2,'de_DE') from suaTabela;

Browser other questions tagged

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