题解 | #判断是否符合 USD 格式#

判断是否符合 USD 格式

https://www.nowcoder.com/practice/667dd00250d04d06989ed1b69102c9ab

      function isUSD(str) {
        // 判断是否有小数点 截取小数点前的整数部分,并以“,”拆分为数组
        let arr;
        if (str.includes(".") && str.includes(",")) {
          // 有小数点就从小数点拆分
          arr = str.slice(0, str.indexOf(".")).split(",");
        }
        if (!str.includes(".") && str.includes(",")) {
          arr = str.split(",");
        }
        if (!str.includes(".") && !str.includes(",")) {
          arr = [str];
        }
        if (str.includes(".") && !str.includes(",")) {
          arr = [str.slice(0, str.indexOf("."))];
        }
        //
        console.log(arr);
        // 判断是否大于三位数,例如$132.03
        let isA;
        let isB;
        if (arr.length <= 1) {
          isA = arr.every(
            (item) =>
              item.slice(0, 1) === "$" &&
              (item.length === 2 || item.length === 3 || item.length === 4) &&
              typeof +item.slice(1) === "number" &&
              !isNaN(+item.slice(1))
          );
        } else {
          // 根据条件返回前面整数部分是否为合法格式
          isA = arr.every((item, index) => {
            if (index === 0) {
              // 当为第一项时,判断长度时2或者3,并且第一项是否为$,后面是否为数字,或者是否为非NaN
              return (
                item.slice(0, 1) === "$" &&
                (item.length === 2 || item.length === 3 || item.length === 4) &&
                typeof +item.slice(1) === "number" &&
                !isNaN(+item.slice(1))
              );
            } else {
              // 当为其他项时只需要判断长度和类型即可
              return (
                item.length === 3 && typeof +item === "number" && !isNaN(+item)
              );
            }
          });
        }
        if (str.includes(".")) {
          isB =
            str.slice(str.indexOf(".")).length === 3 &&
            typeof +str.slice(str.indexOf(".") + 1) === "number" &&
            !isNaN(+str.slice(str.indexOf(".") + 1));
          // 小数点后面的部分,必须为两位数字,带小数点必须为三位,最后再同理判断类型
       
          return isA && isB;
        } else {
          return isA;
        }
      }

全部评论

相关推荐

点赞 评论 收藏
转发
1 收藏 评论
分享
牛客网
牛客企业服务