使用Intl.NumberFormat不四舍五入

时间:2020-10-13 07:31:17

标签: javascript number-formatting

我正在使用Intl.NumberFormat格式化数字:

const formatter = new Intl.NumberFormat('en-US', {
    minimumFractionDigits: 1,
    maximumFractionDigits: 4,
    minimumSignificantDigits: 1,
    maximumSignificantDigits: 4
  })

formatter.format(0.99999) // results: '1'. desired result: '0.9999'
formatter.format(0.006393555) // results: '0.006394'. desired result: '0.006393'
formatter.format(0.9972620384752073) // results: '0.9973'. desired result: '0.9972'
formatter.format(12345.67) // results: '12,350'. desired result: '12,345.67'
formatter.format(200001) // results: '200,000'. desired result: '200,001'

如您所见,数字会自动四舍五入,对于我而言,这是不希望的行为。

有没有办法告诉格式化程序不取整? 我没有found any option或没有多种选择来达成目标。

3 个答案:

答案 0 :(得分:1)

NumberFormat总是四舍五入,但是您可以使用这一额外功能。

function roundDownSignificantDigits(number, decimals) {
  let significantDigits = (parseInt(number.toExponential().split('e-')[1])) || 0;
  let decimalsUpdated = (decimals || 0) +  significantDigits - 1;
  decimals = Math.min(decimalsUpdated, number.toString().length);

  return (Math.floor(number * Math.pow(10, decimals)) / Math.pow(10, decimals));
}

然后

const formatter = new Intl.NumberFormat('en-US', {
  minimumFractionDigits: 1,
  maximumFractionDigits: 4,
  minimumSignificantDigits: 1,
  maximumSignificantDigits: 4
})

结果:

formatter.format(roundDownSignificantDigits(0.99999,4)); // "0.9999"
formatter.format(roundDownSignificantDigits(0.006393555,4)); // "0.006393"
formatter.format(roundDownSignificantDigits(0.9972620384752073,4)); // "0.9972"

答案 1 :(得分:1)

我认为当前规范不可行,并且有few proposals for the new spec,但是您仍然可以使用{ "name": "functions", "description": "Backend - Firebase Cloud Functions", "version": "1.0.0", "scripts": { "lint": "eslint .", "serve": "firebase emulators:start --only functions", "shell": "firebase functions:shell", "start": "npm run shell", "deploy": "firebase deploy --only functions", "logs": "firebase functions:log" }, "engines": { "node": "14.3.0" }, "dependencies": { "config": "^3.3.1", "core-util-is": "^1.0.2", "crypto-js": "^4.0.0", "firebase-admin": "^9.1.1", "firebase-functions": "^3.11.0", "myapp_config": "file:./config" }, "devDependencies": { "eslint": "^5.12.0", "eslint-plugin-promise": "^4.0.1", "firebase-functions-test": "^0.2.0" }, "private": true } 方法并根据需要添加自定义功能来格式化数字部分。

在您的第一个用例中,它可能类似于:

formatToParts

答案 2 :(得分:0)

我可以使用 formatToParts 来获得它。如果需要,您还可以执行一些 javascript 数组函数技巧来分离小数部分。

export const formatNumberWithoutDecimals = (price) =>
  new Intl.NumberFormat(i18n.language, {
    minimumFractionDigits: 2,
  }).formatToParts(price).reduce((result, part) => (part.type !== "decimal" && part.type !== "fraction") ? result + part.value : result, "");