极客时间返利平台,你可以在上边通过山月的链接购买课程,并添加我的微信 (shanyue94) 领取返现。

# 如何取得一个数字的小数部分与整数部分

更多描述

试举几例

  • 1.3e-19
  • 1.6

引用一些第三方包处理也可以

Issue

欢迎在 Gtihub Issue 中回答此问题: Issue 764 (opens new window)

function splitNum(data: unknown): [string, string] {
  if (typeof data === "number" && !isNaN(data)) {
    const dataStr = data.toString();
    const eIndex = dataStr.indexOf("e-");
    if (eIndex > -1) {
      const result = dataStr.split("e-");
      return [
        "0",
        `0.${"0".repeat(Number(result[1]) - 1)}${result[0].replace(".", "")}`,
      ];
    } else {
      const result = dataStr.split(".");
      if (result.length === 1) {
        result.push("0");
      }
      return [result[0], `0.${result[1]}`];
    }
  }
  return ["0", "0"];
}

Author

回答者: Feahter (opens new window)

/**科学计数法兼容*/
const SNFn = (val: string) => {
  let state = val.includes("e-");
  let splitStr = `e${state ? "-" : "+"}`;
  let data = val.split(splitStr);
  let fixBit = Number(data[1]);
  let temp = data[0];
  if (temp.includes(".")) {
    let poinitPosition = temp.indexOf(".");
    let len = temp.length;
    fixBit = fixBit + (poinitPosition + (state ? 0 : 1)) - len;
    temp = `${temp}`.replace(".", "");
  }
  let result = state
    ? `0.${`0`.repeat(fixBit)}${temp}`
    : `${temp}${`0`.repeat(fixBit)}`;
  if (state && result.includes("-")) {
    result = `-${result.replace("-", "")}`;
  }
  return state ? [`0`, result] : [result, `0`];
};

/**main*/
const splitFn = (val: number) => {
  const valStr = `${val}`;
  /**完全整数返回*/
  if (!valStr.includes(".") && !valStr.includes("e")) return [valStr, `0`];
  /**科学计数法兼容*/
  if (valStr.includes("e")) {
    let result = SNFn(valStr);
    return result;
  }
  /**正常含小数返回*/
  const result = valStr.split(".");
  let state = result[0].includes("-");
  return [`${result[0]}`, `${state ? "-" : ""}0.${result[1]}`];
};

https://stackblitz.com/edit/typescript-hr1bbp

Last Updated: 2/15/2022, 12:06:24 PM