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

优雅的处理 人民币单位 #23

Open
JslinSir opened this issue Aug 27, 2022 · 0 comments
Open

优雅的处理 人民币单位 #23

JslinSir opened this issue Aug 27, 2022 · 0 comments

Comments

@JslinSir
Copy link
Owner

JslinSir commented Aug 27, 2022

需求如下

当输入数字的时候,显示数字的最大单位
如: 1,000 在下方展示 千

实现思路

  • 设置单位常量
  • 定位输入数字属于哪一阶段
10 = 10*1 == 1e1
100 = 10*10 == 1e2
1000 = 10*10*10 == 1e3
Math.log10(10) == 1
Math.log10(100) == 2
Math.log10(1000) == 3

根据上面分析10 的幂运算 和对数运算 对应关系
我们定义一个常量

 const charCn = ['个','十','百','千','万','十万','百万','千万','亿','十亿','百亿','千亿','兆','十兆','百兆','千兆','京']

获取值的单位下标

 Math.floor(Math.log10(1))   // 向下取整(取10的对数) 得到的既是 对应值的下标

最后,我们封装个函数

function getCharName(value) {
      const charCnIndex = Math.floor(Math.log10(value)) 
      return charCn[charCnIndex]
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant