Skip to content

Instantly share code, notes, and snippets.

@leocavalcante
Last active December 17, 2015 20:58
Show Gist options
  • Save leocavalcante/5671054 to your computer and use it in GitHub Desktop.
Save leocavalcante/5671054 to your computer and use it in GitHub Desktop.
number format API example
<!-- prefix : thousands : decimals : numdecimals : sufix -->
<!-- $ 1,234.567 -->
<input type="text" data-numformat="$ :comma:dot:3:">
<!-- R$ 1.234,56 reais -->
<input type="text" data-numformat="R$ :dot:comma:2: reais">
<!-- 1234.56 -->
<input type="text" data-numformat="::dot:2:">
<!-- 1.234 -->
<input type="text" data-numformat=":dot:::">
@millermedeiros
Copy link

pensando melhor acho que até removeria o k, d e n já que se vc definiu delimitador para thousands provavelmente tbm precisa delimitar para decimals e numdecimals tem que ser um numeral...

<input type="text" data-numformat="R$ |.,3| reais">
var currencyFormat = require('mout/number/currencyFormat');


function format(val, pattern){
    pattern = pattern || '||';
    var re = /\|(.*)\|/;
    var config = pattern.match(re);
    var digits, decimal, thousands;
    if (config && config[1]) {
        config = config[1];
        decimal = getConfig(config, /[^\d]([^\d])/);
        digits = getConfig(config, /(\d+)/);
        thousands = getConfig(config, /([^\d])/);
    }
    val = currencyFormat(val, digits, decimal, thousands);
    return config? pattern.replace(re, val) : pattern + val;
}


function getConfig(config, re){
    var match = re.exec(config);
    return match? match[1] : null;
}


console.log( format(1234.56, 'R$ |.,3| reais') );
//> "R$ 1.234,560 reais"
console.log( format(1234.56, '$|,.|') );
//> "$1,234.56"
console.log( format(1234.56, '$|1|') );
//> "$1,234.6"
console.log( format(1234.56, '$') );
//> "$1,234.56"
console.log( format(1234.56) );
//> "1,234.56"

@leocavalcante
Copy link
Author

Legal. Ficou interessante nesse ultimo jeito.

@suissa
Copy link

suissa commented May 30, 2013

Também prefiro a ultima forma :D

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment