我用默认的数字js格式存储数字和货币格式。我允许用户根据其区域设置拥有自己的格式设置。我试图弄清楚如何将它们的自定义格式转换回默认格式,以便一致地存储它,以防它们更改区域设置。
例如,设置当前:
numeral.register('locale', 'fr', {
delimiters: {
thousands: '.',
decimal: ','
},
abbreviations: {
thousand: 'k',
million: 'm',
billion: 'b',
trillion: 't'
},
ordinal : function (number) {
return number === 1 ? 'er' : 'ème';
},
currency: {
symbol: '€'
}
});当我得到‘0.000欧元’作为首选格式时,我如何转换回到默认的numeral.js设置为‘0,0.00美元’的存储。
发布于 2017-05-12 12:04:59
您可以简单地通过使用numeral.local('en')设置本地设置来在本地之间切换。你可以用一个小助手函数来帮你做这件事。您只需传递所需的本地数字,也许您当前的数字,您需要切换。
下面就是一个这样的例子。我还增加了money.js以在货币之间进行换算。我相信你会明白的。
var yourNumeral = numeral(1234.56);
// helper fn to switch local and convert.
function switchLocal(local, num, convert) {
numeral.locale(local);
num.set(fx.convert(num.value(), convert));
return num.format();
}
// set money.js base and rates
fx.base = "EUR";
fx.rates = {
"USD" : 1.0873 // eg. 1 EUR === 1.0873 USD
};
// set default format.
numeral.defaultFormat('0,0[.]00 $');
// load a locale.
numeral.register('locale', 'fr', {
delimiters: {
thousands: ' ',
decimal: ','
},
abbreviations: {
thousand: 'k',
million: 'm',
billion: 'b',
trillion: 't'
},
ordinal : function (number) {
return number === 1 ? 'er' : 'ème';
},
currency: {
symbol: '€'
}
});
// set the loaded local.
numeral.locale('fr');
// yourNumeral with loaded local "fr".
console.log(yourNumeral.format());
// yourNumeral switched local to "en" and converted from € to $.
console.log(switchLocal('en', yourNumeral, { from: "EUR", to: "USD" }));
// yourNumeral switched back to "fr" local and converted back to € from $.
console.log(switchLocal('fr', yourNumeral, { from: "USD", to: "EUR" }));<script src="https://openexchangerates.github.io/money.js/money.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/numeral.js/2.0.6/numeral.min.js"></script>
https://stackoverflow.com/questions/43934262
复制相似问题