首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用numeral.js将地区设置格式转换为默认格式

使用numeral.js将地区设置格式转换为默认格式
EN

Stack Overflow用户
提问于 2017-05-12 09:34:05
回答 1查看 4.7K关注 0票数 2

我用默认的数字js格式存储数字和货币格式。我允许用户根据其区域设置拥有自己的格式设置。我试图弄清楚如何将它们的自定义格式转换回默认格式,以便一致地存储它,以防它们更改区域设置。

例如,设置当前:

代码语言:javascript
复制
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美元’的存储。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-05-12 12:04:59

您可以简单地通过使用numeral.local('en')设置本地设置来在本地之间切换。你可以用一个小助手函数来帮你做这件事。您只需传递所需的本地数字,也许您当前的数字,您需要切换。

下面就是一个这样的例子。我还增加了money.js以在货币之间进行换算。我相信你会明白的。

代码语言:javascript
复制
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" }));
代码语言:javascript
复制
<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>

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43934262

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档