zoukankan      html  css  js  c++  java
  • js 实现简单的parseInt和parseFloat

    function myParseInt(str: string): number {
      let result = NaN;
      for (let i = 0; i < str.length; i++) {
        const dec: number = str.charCodeAt(i);
        if (dec < 48 || dec > 57) break;
        if(isNaN(result)) result = 0;
    
        const value = dec - 48;
        result = result * 10 + value;
      }
      return result;
    }
    
    function myParseFloat(str: string): number {
      let result = NaN;
      let isDecimal = false; // 小数点
      let decimalIndex = 0; // 小数点第几位
      const N = 1000;
      for (let i = 0; i < str.length; i++) {
        const dec: number = str.charCodeAt(i);
        const isPoint = dec === 46;
    
        if (isPoint && isDecimal) {
          // 再次遇到小数点直接返回
          break;
        } else if (isPoint) {
          isDecimal = true;
          continue;
        }
    
        if (dec < 48 || dec > 57) break;
        if (isNaN(result)) result = 0;
    
        const value = dec - 48;
    
        if (!isDecimal) {
          result = result * 10 + value;
        } else {
          decimalIndex++;
          result = (result * N + (value / 10 ** decimalIndex) * N) / N;
        }
      }
      return result;
    }
    
    console.log(myParseInt("12.22")); // 12
    console.log(myParseFloat("0.22")); // 0.22
    
  • 相关阅读:
    4.7字符串
    4.5 基本类型和运算符
    4.4 变量
    4.6 字符串
    hp
    openstack newton linuxbridge 改成 ovs
    理解裸机部署过程ironic
    csredis base usage
    redisclient can not connect
    Linux Install redis
  • 原文地址:https://www.cnblogs.com/ajanuw/p/14113139.html
Copyright © 2011-2022 走看看