numbro icon indicating copy to clipboard operation
numbro copied to clipboard

How to format the value into ten-thousandths style?

Open minikinl opened this issue 3 years ago • 2 comments

we can use 0,0 to format the value as thousandths now:

numbro(123456).format("0,0")
// output: 123,456

but, how to format it into ten-thousandths?

numbro(123456).format("0,0000")
// expect: 12,3456

There is an example with cleave.js :

截屏2021-08-02 上午10 25 12

BTW, space-separate style is also very common,what if it is supported?

numbro(123456).format("0 0")
// expect: 123 456

minikinl avatar Aug 02 '21 02:08 minikinl

You can change languageData delimiters of numbro.

setDelimiters(" ", 4);
console.log(numbro(123456).format({thousandSeparated: true})); // 12 3456
setDelimiters(",", 2);
console.log(numbro(123456).format({thousandSeparated: true})); // 12,34,56
setDelimiters();
console.log(numbro(123456).format({thousandSeparated: true})); // 123,456

function setDelimiters(delimiter = ",", size = 3) {
    numbro.languageData().delimiters.thousands = delimiter;
    numbro.languageData().delimiters.thousandsSize = size;
}

AlisaLC avatar Dec 25 '21 04:12 AlisaLC

@AlisaLC Thank you so much! The sample code you provided can work on numbro@latest.

The bad thing is that I am using [email protected] and this code throws an exception:

console.log(numbro(123456).format({thousandSeparated: true}));
Uncaught TypeError: format.replace is not a function
    at formatNumbro (/Users/mozhs/workbench/next-smartfe/node_modules/numbro/numbro.js:188:36)
    at Numbro.format (/Users/mozhs/workbench/next-smartfe/node_modules/numbro/numbro.js:1156:20)

My solution is to extend numbro.fn:

try {
  // numbro.fn === Numbro.prototype in [email protected]
  const proto = numbro.fn;
  const protoFormat = proto.format;
  proto.format = function (inputString, roundingFunction) {
    if (String(inputString).match(/,0{4,}/)) {
      return formatTenThousandths(this, inputString, roundingFunction);
    }
    return protoFormat.call(this, inputString, roundingFunction);
  };
} catch (err) {
  // @todo: error handling
}

minikinl avatar Dec 28 '21 04:12 minikinl