高级前端js【Q737】如何取得一个数字的小数部分与整数部分

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

更多描述 试举几例

  • 1.3e-19
  • 1.6

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

Issue 欢迎在 Gtihub Issue 中回答此问题: Issue 764

Author 回答者: heretic-G

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

/**科学计数法兼容*/
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