-
-
Notifications
You must be signed in to change notification settings - Fork 3.3k
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
[js] 第59天 写一个格式化金额的方法 #246
Comments
为啥题目描述总这么含糊不清。。。 var number = 123456.789;
new Intl.NumberFormat('en-GB', { style: 'currency', currency: 'USD' }).format(number)
// expected output: "US$123,456.79" 感谢 @SCLeoX 提醒 |
其他方法还包括 |
你这个不行啊,significantDigits 设置成 3 的意思是只保留三位数。这个并不是说多少位一逗号的... |
@thisisandy 题目需要你自己审下,正如我们实际工作中,产品经理不可能所有的情况都给你列出来。其实格式化金额的细节还不少,这道题也在于考查分析题的能力,要不然返工的情况就会很多。
|
function moneyFormal(m){
return m.toLocaleString()
} |
@myprelude 什么胡任务?不明白 |
这个有这么简单吗? |
@haizhilin2013 我想到就是这个办法, 胡任务就是我调侃不要在意 |
@myprelude 呵呵,我没在意,我只是不知道胡任务是什么意思而已,今天第一听到这个词,所以就特意问问。嘿嘿 |
@haizhilin2013 老家话大意是:没有之前工作的状态当做每天任务在完成了。形容人做事不认真懒散了,没有责任心了。感觉说的有点过了,我已经删除了。见谅口头禅了 |
@myprelude 呵呵,原来是这个意思啊!学习了!没事,放着就好,又get到新知识了,非常感谢!这些题都很好的,你们答可能就几分钟,我出一道题可能要花上个10多分钟想……嘿嘿,加油!看似越简单的题包含的信息量就越大 |
@myprelude 这道题有时间可以在好好想想!你直接就用toLocaleString是不行的! |
|
toFixed() 浮点数陷阱 怎么处理的
|
一直都是使用tolocalestring |
这个case很常见, 这个需要考虑的情况确实太多了。 |
|
function formatPrice(val, spacer = ',') {
const typeVal = typeof val
if (typeVal !== 'string' && typeVal !== 'number') return val
let _val = '' + val
return _val.replace(/\B(?=(\d{3})+\b)/g, spacer)
}
console.log(formatPrice(123))
console.log(formatPrice(1234))
console.log(formatPrice(12345))
console.log(formatPrice(123456))
console.log(formatPrice(1234567))
console.log(formatPrice(123.23))
console.log(formatPrice(1234.23))
console.log(formatPrice(1235.23))
console.log(formatPrice(12356.23))
console.log(formatPrice(123567.23))
console.log(formatPrice(123567890.23))
// 123
// 1,234
// 12,345
// 123,456
// 1,234,567
// 123.23
// 1,234.23
// 1,235.23
// 12,356.23
// 123,567.23
// 123,567,890.23 |
let str = "100000000000000";
let reg = /(?=(\B)(\d{3})+$)/g;
console.log(str.replace(reg, '.')); |
如果是3位数字转逗号那种的话
|
|
// NaN处理为-,逗号分隔,保留两位,向下取整,补全两位小数
const format = (value) => {
let num = parseFloat(value)
if (isNaN(num)) {
console.error(new Error('NaN'))
return '-'
}
num = Math.floor(num * 100) / 100
num = num.toLocaleString()
const decimal = num.match(/\.\d+/g)
if (decimal) {
num = num.replace(/\.\d+/g, decimal[0].padEnd(3, '0'))
} else {
num += '.00'
}
return '¥' + num
}
console.log(format(1))// ¥1.00
console.log(format(1.3))// ¥1.30
console.log(format(23231.45))// ¥23,231.45
console.log(format('1.456d'))// ¥1.45
console.log(format('dddd'))// - |
toLocaleString |
第59天 写一个格式化金额的方法
The text was updated successfully, but these errors were encountered: