首页 > 解决方案 > NodeJS 如何用 . 和零?

问题描述

假设我们有数字 300,我希望将其填充为 300.000

或者数字 23,5 类似于 23.500

标签: javascriptnode.js

解决方案


希望对您有所帮助,详情见评论。

function formating(n) {
  // Convert number into a String
  const str = n.toString();
  // Find the position of the dot.
  const dotPosition = str.search(/\./);
  // Return string with the pad.
  if (dotPosition === -1) {
    return str += ".000";
  } else {
    const [part1, part2] = str.split('.');
    return part1 + '.' + part2.padEnd(3, "0");
 }
}

推荐阅读