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

[js] 第59天 写一个格式化金额的方法 #246

Open
haizhilin2013 opened this issue Jun 13, 2019 · 23 comments
Open

[js] 第59天 写一个格式化金额的方法 #246

haizhilin2013 opened this issue Jun 13, 2019 · 23 comments
Labels
js JavaScript

Comments

@haizhilin2013
Copy link
Collaborator

第59天 写一个格式化金额的方法

@thisisandy
Copy link

thisisandy commented Jun 14, 2019

为啥题目描述总这么含糊不清。。。
如果是格式成三位一逗的话

var number = 123456.789;
new Intl.NumberFormat('en-GB', { style: 'currency', currency: 'USD' }).format(number)
// expected output: "US$123,456.79"

感谢 @SCLeoX 提醒
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat

@thisisandy
Copy link

其他方法还包括 toLocalString 或者使用正则匹配 /[0-9](?=(?:[0-9]{3})+(?![0-9]))/g

@SCLeoX
Copy link

SCLeoX commented Jun 14, 2019

为啥题目描述总这么含糊不清。。。
如果是格式成三位一逗的话

var number = 123456.789;
new Intl.NumberFormat('en-IN', { maximumSignificantDigits: 3 }).format(number))
// expected output: "1,23,000"

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat

你这个不行啊,significantDigits 设置成 3 的意思是只保留三位数。这个并不是说多少位一逗号的...

@haizhilin2013
Copy link
Collaborator Author

haizhilin2013 commented Jun 14, 2019

@thisisandy 题目需要你自己审下,正如我们实际工作中,产品经理不可能所有的情况都给你列出来。其实格式化金额的细节还不少,这道题也在于考查分析题的能力,要不然返工的情况就会很多。
例如:

  1. 用逗号分隔
  2. 前面有0时,如:03
  3. 前端有“.”时,如:.3
  4. 输入的是非数字和.时
  5. 要保留的不一定是2位,还有可能是1位,或者不要小数点
  6. 如果要保留两位,如果位数不足是否要补0
  7. 要四舍五入吗?还是向上取整?还是向下取整?还是……
  8. 是否要加金额符号¥
  9. ……
    当然你有可能会说这样开发效率会很慢,而且问题很多,不可能全部想全,但是以往的经验告诉我们,如果需求捋得很清楚,编码只不过仅仅是个体力活而已,而且返工率很少,质量就变得很高了。也可以早点下班了!很多的时候我们在修改bug的时间比写代码的时间还多的多,不是吗?

@haizhilin2013 haizhilin2013 pinned this issue Jun 14, 2019
@haizhilin2013 haizhilin2013 unpinned this issue Jun 14, 2019
@myprelude
Copy link

function moneyFormal(m){
  return m.toLocaleString()
}

@haizhilin2013
Copy link
Collaborator Author

@myprelude 什么胡任务?不明白

@haizhilin2013
Copy link
Collaborator Author

function moneyFormal(m){
  return m.toLocaleString()
}

这个有这么简单吗?

@myprelude
Copy link

@haizhilin2013 我想到就是这个办法, 胡任务就是我调侃不要在意

@haizhilin2013
Copy link
Collaborator Author

@myprelude 呵呵,我没在意,我只是不知道胡任务是什么意思而已,今天第一听到这个词,所以就特意问问。嘿嘿

@myprelude
Copy link

@haizhilin2013 老家话大意是:没有之前工作的状态当做每天任务在完成了。形容人做事不认真懒散了,没有责任心了。感觉说的有点过了,我已经删除了。见谅口头禅了

@haizhilin2013
Copy link
Collaborator Author

@myprelude 呵呵,原来是这个意思啊!学习了!没事,放着就好,又get到新知识了,非常感谢!这些题都很好的,你们答可能就几分钟,我出一道题可能要花上个10多分钟想……嘿嘿,加油!看似越简单的题包含的信息量就越大

@haizhilin2013
Copy link
Collaborator Author

@haizhilin2013 我想到就是这个办法, 胡任务就是我调侃不要在意

@myprelude 这道题有时间可以在好好想想!你直接就用toLocaleString是不行的!

@yxkhaha
Copy link

yxkhaha commented Jun 14, 2019

function Format(num) {
    var str = '¥';
    var decimal = num.toFixed(2);
     str += parseFloat(decimal);
     return str
  }

@xn213
Copy link

xn213 commented Jun 14, 2019

toFixed() 浮点数陷阱 怎么处理的

function Format(num) {
    var str = '¥';
    var decimal = num.toFixed(2);
     str += parseFloat(decimal);
     return str
  }

Format(12.345) // "¥12.35"
Format(12.556) // "¥12.56"
Format(12.565) // "¥12.56"
12.556 - 12.565 = 0.009 差值

@haizhilin2013 haizhilin2013 added the js JavaScript label Jun 18, 2019
@Cillivian
Copy link

一直都是使用tolocalestring

@jiamianmao
Copy link

这个case很常见,https://ant.design/components/input-number-cn/ 通常在中后台项目中使用这个。

这个需要考虑的情况确实太多了。

@laixihong
Copy link

function getLoan(loan){
        let Num = Number(loan).toString();
        let arr = Num.split(".");
        let result = ""
        let zs = Number(arr[0]);
        let xs = arr[1]
        while (zs >= 1000){
            result = "," + zs % 1000 + result;
            zs = Math.floor(zs/1000)
        }
        result = zs + result;
        if(xs){
            result += "."
            while(xs.length > 3){
                result += xs.slice(0,3) + ","
                xs = xs.slice(3);
            }
            result += xs
        }

        return result
    }

@rni-l
Copy link

rni-l commented Jan 19, 2020

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

@276378532
Copy link

        let str = "100000000000000";
        let reg = /(?=(\B)(\d{3})+$)/g;
        console.log(str.replace(reg, '.'));

@wepn13232
Copy link

wepn13232 commented Dec 14, 2020

如果是3位数字转逗号那种的话

let num = 100000;
//下方的转localString可任选一个
let num1 = num.toLocalString('de-DE'); //德国以 . 分割金钱, 转到德国当地格式化方案即可
let num2 = num.toLocalString();
let price = num2.replace(/,/g,'.'); //替换分隔符即可

@MrZ2019
Copy link

MrZ2019 commented Dec 15, 2020

var number = 123456.789;
new Intl.NumberFormat('en-GB', { style: 'currency', currency: 'USD' }).format(number)

@wind8866
Copy link

wind8866 commented Mar 3, 2022

// 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'))// -

@xiaoqiangz
Copy link

toLocaleString

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

No branches or pull requests