国际上相当的包含小数的打印字符串对象

时间:2014-04-06 20:29:55

标签: javascript string internationalization decimal pretty-print

我使用MikeMcl's big.js进行精确会计,在调用toFixed()时输出一个字符串。

我希望以国际化的方式打印小数结果,就像Date Object如何以本地格式自动打印datestimes一样。

有没有办法格式化包含国际小数的字符串对象?

2 个答案:

答案 0 :(得分:1)

var myNumber = 123456.78;
console.log(myNumber.toLocaleString());

答案 1 :(得分:1)

这应该可以胜任。

function localize(fixed) {
  /*Determine decimal symbol and digit grouping symbol.*/
  var decimalSymbol = '.';
  var digitGroupingSymbol = ',';
  var dummy = 1234.5;
  testResult = dummy.toLocaleString();
  /*Browsers using digit grouping symbol.*/
  if (testResult.length === 7) {
    decimalSymbol = testResult[5];
    digitGroupingSymbol = testResult[1];
  }
  /*Browsers not using digit grouping symbol.*/
  if (testResult.length === 6) {
    decimalSymbol = testResult[4];
    digitGroupingSymbol = (decimalSymbol === '.'? ',': '.');
  }
  /*Format the number.*/
  var result = '';
  var dsIndex = fixed.indexOf('.');
  if (dsIndex < 0) {
    throw new Error('Expected decimal separator \'.\' in "' + fixed + '".');
  }
  for (var i = 0; i < dsIndex; ++i) {
    if (fixed[i] < '0' || fixed[i] > '9') {
      throw new Error('Expected digit, got "' + fixed[i] + '".');
    }
    if (i > 0 && i%3 === dsIndex%3) result += digitGroupingSymbol ;
    result += fixed[i];
  }
  result += decimalSymbol + fixed.substr(dsIndex + 1);
  return result;
}  

/*Demonstration*/
var n1 = '123.4567890';
console.assert(localize(n1));
var n2 = '1234.567890';
console.log(localize(n2));
var n3 = '123456789012345678.1234567890';
console.log(localize(n3));
var n4 = '1234567890123456789.1234567890';
console.log(localize(n4));
var n5 = '12345678901234567890.1234567890';
console.log(localize(n5));

输出:
123.4567890
1.234.567890
123.456.789.012.345.678.1234567890
1.234.567.890.123.456.789.1234567890
12.345.678.901.234.567.890.1234567890