Last active
December 17, 2015 20:58
-
-
Save leocavalcante/5671054 to your computer and use it in GitHub Desktop.
number format API example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- 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:::"> |
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"
Legal. Ficou interessante nesse ultimo jeito.
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
eu acho que usaria algo mais minimalista e com os argumentos opicionais:
mout/number/currencyFormat