Skip to content

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

Open
@haizhilin2013

Description

@haizhilin2013
Collaborator

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

Activity

thisisandy

thisisandy commented on Jun 14, 2019

@thisisandy

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

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

thisisandy commented on Jun 14, 2019

@thisisandy

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

SCLeoX

SCLeoX commented on Jun 14, 2019

@SCLeoX

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

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

haizhilin2013 commented on Jun 14, 2019

@haizhilin2013
CollaboratorAuthor

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

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

myprelude commented on Jun 14, 2019

@myprelude
function moneyFormal(m){
  return m.toLocaleString()
}
haizhilin2013

haizhilin2013 commented on Jun 14, 2019

@haizhilin2013
CollaboratorAuthor

@myprelude 什么胡任务?不明白

haizhilin2013

haizhilin2013 commented on Jun 14, 2019

@haizhilin2013
CollaboratorAuthor
function moneyFormal(m){
  return m.toLocaleString()
}

这个有这么简单吗?

myprelude

myprelude commented on Jun 14, 2019

@myprelude

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

haizhilin2013

haizhilin2013 commented on Jun 14, 2019

@haizhilin2013
CollaboratorAuthor

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

myprelude

myprelude commented on Jun 14, 2019

@myprelude

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

haizhilin2013

haizhilin2013 commented on Jun 14, 2019

@haizhilin2013
CollaboratorAuthor

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

haizhilin2013

haizhilin2013 commented on Jun 14, 2019

@haizhilin2013
CollaboratorAuthor

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

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

yxkhaha

yxkhaha commented on Jun 14, 2019

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

xn213 commented on Jun 14, 2019

@xn213

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 差值

Cillivian

Cillivian commented on Jul 26, 2019

@Cillivian

一直都是使用tolocalestring

jiamianmao

jiamianmao commented on Aug 11, 2019

@jiamianmao

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

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

laixihong

laixihong commented on Dec 24, 2019

@laixihong
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

rni-l commented on Jan 19, 2020

@rni-l
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

276378532 commented on Aug 21, 2020

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

wepn13232 commented on Dec 14, 2020

@wepn13232

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

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

smile-2008

smile-2008 commented on Dec 15, 2020

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

wind8866 commented on Mar 3, 2022

@wind8866
// 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

xiaoqiangz commented on Jun 10, 2022

@xiaoqiangz

toLocaleString

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    jsJavaScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @smile-2008@haizhilin2013@thisisandy@SCLeoX@xiaoqiangz

        Issue actions

          [js] 第59天 写一个格式化金额的方法 · Issue #246 · haizlin/fe-interview