Decimal format in monetary value [duplicate]

3

    
asked by anonymous 20.08.2015 / 04:31

2 answers

2

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 number_format function is the PHPJS.org project: link

This project translates PHP functions into the JavaScript language.

The number_format function has the same characteristics as the original in PHP: link

Parameters nomenclature is self-defeating

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.

Example, when you format a decimal value that is set to be displayed without the decimal places, evaluate whether the business model requires rounding up or down. In these cases, you must implement with the functions ceil() or floor() or whichever is more appropriate.

    
20.08.2015 / 11:23
1

Well, I have done a function in the same hand I will post the two cases, float to currency , and / em>:

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 this case I will demonstrate in mysql :

select format(suaColuna,2,'de_DE') from suaTabela;
    
20.08.2015 / 13:17