JavaScript数字格式

The task

任务

A number given should be formatted for easy reading by separating digits into triads. Format must be made inline via JavaScript, i.e., frameworks / functions are not welcome.

给定的数字应设置格式以便于读取,方法是将数字分成三个字母。 格式必须通过JavaScript内联,即不欢迎使用框架/函数。

So let’s take a number like this “12345678.91¿ and format it to “12 345 678.91¿. To be shorter I assign it to a variable and hustled up following line which produced desired format:

因此,让我们采用类似“ 12345678.91”的数字并将其格式化为“ 12 345 678.91”。 为了简短起见,我将其分配给一个变量,然后按照产生所需格式的行进行处理:

> var n = "12345678.91";
> n.split('').reverse().join('').match(/.{1,3}/g).join(' ').split('').reverse().join('').replace(/\s\.|,\./g, '.'));
> "12 345 678.91"

How it’s made

这个怎么做的

First there is a string that has to be split somehow into triad. This is pretty simple – I’ve just used Regular expression with match and join methods to get the result back into a string using desired digital group separator (space in the case):

首先,有一个字符串必须以某种方式拆分为三重奏。 这非常简单–我刚刚使用带有matchjoin方法的正则表达式使用所需的数字组分隔符(在情况下为空格)将结果返回到字符串中:

> n.match(/.{1,3}/g).join(' ');
> "123 456 78. 91"
replace function. 替换功能。
> n.match(/.{1,3}/g).join(' ').replace(/\.\s/g, '.');
> "123 456 78.91"
> n.split('').reverse().join('').match(/.{1,3}/g).join(' ');
> "19. 876 543 21"
> n.split('').reverse().join('').match(/.{1,3}/g).join(' ').split('').reverse().join('');
> "12 345 678 .91"
> n.split('').reverse().join('').match(/.{1,3}/g).join(' ').split('').reverse().join('').replace(/\s\./g, '.');
> "12 345 678.91"

Some final thoughts:

最后的想法:

What if we have a number instead of a string?

如果我们用数字而不是字符串怎么办?

var n = 12345678.91;Applying the long line just composed against a number will produce an error…

var n = 12345678.91;对数字仅应用长线会产生错误…

Solution?

解?



Just add one more step in front of all the others:

只需在所有其他步骤的前面再增加一个步骤:

> n.toFixed(2).split('').reverse().join('').match(/.{1,3}/g).join(' ').split('').reverse().join('').replace(/\s\./g, '.'); > "12 345 678.91"

> n.toFixed(2).split('')。reverse()。join('')。match(/。{1,3} / g).join('').split('')。reverse ().join('')。replace(/ \ s \ ./ g,'。'); >“ 12 345 678.91”

What if a number is required as result?

如果需要输入数字怎么办?



Right! Still another step – multiplication by 1 – at the end.

对! 最后还有一步-乘以1。

> n.toFixed(2).split('').reverse().join('').match(/.{1,3}/g).join(' ').split('').reverse().join('').replace(/\s\./g, '.')*1; > 12 345 678.91

> n.toFixed(2).split('')。reverse()。join('')。match(/。{1,3} / g).join('').split('')。reverse ().join('')。replace(/ \ s \ ./ g,'。')* 1; > 12345 678.91

Now you know how it's made ;-)

现在您知道它是如何制成的;-)

翻译自: https://www.experts-exchange.com/articles/8195/Javascript-number-formating.html

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值