quarta-feira, 10 de junho de 2015

Formatar números decimais com PostgreSQL

Nesta postagem quero compartilhar com vocês uma função para formatar números decimais em PostgreSQL.

create or replace function format_number (_number numeric, decimals integer, decimal_symbol char, thousands_symbol char)
  returns varchar as
$BODY$
declare
    _value varchar;
    _index integer;
    _values varchar[2];
    i integer;
    pos integer;
begin
    _value = round(_number, decimals)::varchar;
    _index = strpos(_value, '.');

    _values[0] = _value;
    _values[1] = '';
    if (_index > 0) then
        _values[0] = substr(_value, 0, _index);
        _values[1] = decimal_symbol || substr(_value, _index+1);        
    end if;
    
    i = 0;
    while (i < floor((length(_values[0]) - (i+1)) / 3)) loop
        pos = length(_values[0]) - (4 * i+2);
        _values[0] = substr(_values[0], 0, pos) || thousands_symbol || substr(_values[0], pos);    
        i = i+1;
    end loop;
    
    return _values[0] || _values[1];
end;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100; 

Exemplo de uso:

SELECT format_number(minha_coluna) FROM minha_tabela