Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【Q737】如何取得一个数字的小数部分与整数部分 #764

Open
shfshanyue opened this issue Feb 5, 2022 · 2 comments
Open
Labels

Comments

@shfshanyue
Copy link
Owner

shfshanyue commented Feb 5, 2022

试举几例

  • 1.3e-19
  • 1.6

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

@shfshanyue shfshanyue added the js label Feb 5, 2022
@heretic-G
Copy link

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']
}

@Feahter
Copy link

Feahter commented Feb 9, 2022

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants