-
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
第 143 题:将'10000000000'形式的字符串,以每3位进行分隔展示'10.000.000.000',多种实现方式 #296
Comments
var str = '10000000000'; |
const splitStr = (str, point = 3, split = '.') => {
let newStr = '';
const reverseStr = str.split('').reverse().join('');
for (const s in reverseStr) {
newStr = (s !== '0' && s % point === 0) ? newStr + split + reverseStr[s] : newStr + reverseStr[s];
}
return newStr.split('').reverse().join('');
} |
如果一行写不出来,我选择不写 // 德国以 . 分割金钱, 转到德国当地格式化方案即可
10000000000..toLocaleString('de-DE')
// 寻找字符空隙加 .
'10000000000'.replace(/\B(?=(\d{3})+(?!\d))/g, '.')
// 寻找数字并在其后面加 .
'10000000000'.replace(/(\d)(?=(\d{3})+\b)/g, '$1.') |
var myNum = Number('10000000000'); //字符串转数字后就可以使用toLocaleString()啦~ var num2Str = myNum .toLocaleString(); //"10,000,000,000" num2Str.replace(/,/g, "."); //"10.000.000.000" 哭了,这么好的方法竟然这么多人踩 |
应该是考金额的转换吧,考虑到小数点的情况,如下: |
笨方法function addCommaIntoStringNumber(sNumber, splitNumber = 3){
if (sNumber.length <= splitNumber) {
return sNumber
}
let result = []
let sNumberQuene = sNumber.split('')
let index = 1
let sNumberLength = sNumber.length
while(sNumberLength--) {
result.unshift(sNumberQuene.pop())
if (index++ === splitNumber) {
result.unshift(',')
index = 1
}
}
return result.join('')
} |
类似金额的转化,这里相对还要简单一些 |
如果主要想考数字的千位分隔符表示法,可以使用正则 |
str.split("").reverse().reduce((prev, cur, index) => (index + 1) % 3 == 0 ? '.' + cur + prev : cur + prev) |
// 正则不大会...只好一步步来
function foo(num) {
const arr = [...num].reverse();
const rst = arr.reduce((init, ele, i) => {
i % 3 === 2 ? init.push(ele, '.') : init.push(ele);
return init;
}, []);
return rst.reverse().join('')
} |
// 保留两位小数后添加千分位符
getEffective = str => {
let [int, decimal] = String(Number(str).toFixed(2)).split('.')
let res =
[...int]
.reverse()
.reduce(
(prev, item, index) => (
prev.push(index % 3 === 2 ? ',' + item : item), prev
),
[]
)
.reverse()
.join('') + `.${decimal}`
if (res[0] === ',') {
return res.slice(1)
}
return res
} |
var str= '10000000000'; |
"1000000000000".split('').reverse().reduce((total, each, i)=>{
total.push(each)
if ((i + 1) % 3 == 0) total.push('.')
return total
}, []).reverse().join('') |
new Intl.NumberFormat().format(100000000000).replace(/,/g, '.'); |
|
|
var reg = /(\B)(?=(\d{3})+$)/g;
console.log("1000000000".replace(reg, '.')); // 1.000.000.000 |
|
str.replace(/\d(?=(\d{3})+$)/g, '$&.'); |
有没有考虑到1刚好可以除尽的情况, 就会 .100.000.000.00 |
哪位大神能帮忙解释一下第一种方法为什么有两个点.. |
因为数字后面接第一个 |
let str = '1000000000000'
let result = [...str].reverse().map( (v, i) => {
if (i % 3 === 0 && i !== 0) {
return `${v}.`
}
return v
}).reverse().join("") |
应该是酸你想得出来自己想不出来所以就踩了哈哈 |
'10000000'.replace(/(?!^)(?=(\d{3})+$)/g, '.') |
Number('1000000000').toLocaleString().replace(/,/g, '.') |
不会正则就用粗旷的方式吧
|
'100000000'会输出'.100.000.000' |
let reg = /(?!^)(?=(\d{3})+$)/g |
Number(100000000000).toLocaleString('de-DE') |
87463297 =>"87,463,297"
"87463297".replace( /\d{1,3}(?=(\d{3})+$)/g , (s)=>s+',')
/\d{1,3}(?=(\d{3})+$)/g ,//找出后面跟有三个数字的,即["87", "463"],添加逗号在后面即可
\d{1,3} //1-3位数字
(?=(\d{3})+$) //?=表示后面要跟着符合(\d{3})+$的, 即1个或多个(3个数字)结尾的 |
// 从后向前遍历,每次截取三个字符,直到完成
const str = '10000000000';
const arr = [];
for (let len = str.length, i = len - 1; i >= 0; i = i - 3) {
let start = i - 2;
if (start < 0) start = 0;
arr.push(str.slice(start, i + 1));
}
return arr.reverse().join('.'); |
笑死我了,运行过吗? |
有点问题 |
const thousandSeparator = (num) => {
let tstr = num.toString()
let res = ''
let count = 0
for (let i = tstr.length - 1; i >= 0; i--) {
res += tstr[i]
++count
if (count % 3 === 0 && i !== 0) {
res += '.'
}
}
res = res.split('').reverse().join('')
return res
} |
考虑符号和小数位,用的笨办法
|
const regex = /(?<!^)(?=(\d{3})+$)/g;
const s = '123456789';
s.replace(regex, ','); |
/**
* @param {String} str
* @return {String}
*/
function separate(str) {
const arr = str.split('')
for (let i = arr.length - 3; i > 0; i -= 3) {
arr[i] = `.${arr[i]}`
}
return arr.join('')
}
const res = separate('100000000')
console.log('res: ', res) |
'10000000000' |
Number('100000000').toLocaleString() |
可以这么写 |
"1000000000000".split("").reverse().reduce((prev, next, index) => {
if(index > 0 && index % 3 == 0) {
return next = next + '.' + prev
} else {
return next + prev
}
}, '') |
const fond07 = (str) => { |
考虑数字是三的倍数情况 function splitNum(str) {
return str.replace(/(\d)(?=(\d{3})+$)/g, '$1.');
} |
const transStr = str => str.split('')
.reduceRight((result, word, index, arr) =>
((index + 1) % 3 === 0 && index !== arr.length - 1 ? '.' : '' )
+ word + result) |
function format(str) {
const reverse = str.toString().split('').reverse().join('');
return reverse.replace(/(\d{3})/g, '$1,').replace(/\,$/g, '').split('').reverse().join('');
} |
'-1019234801211.2142345678'.replace(/(?<!...)(\d)(?=(\d{3})+($|.))/g, '$1,') |
ts的实现方法: 方法一(推荐):
方法二:
|
正则 '10000000000'.replace(/(\d)(?=(\d{3})+$)/g, '$1.') 国际化 new Intl.NumberFormat('de-DE').format(100000000000) toLocaleString 100000000000..toLocaleString('de-DE') |
|
'10000000000'.replace(/\d(?=(\d{3})+$)/g, '$&.') |
'10000000000'.replace(/(\d)(?=(\d{3})+$)/g, '$1.') |
function format(str) {
return str
.split('')
.reverse()
.reduce((acc, cur, index) =>
index % 3 === 0 ? `${cur}.${acc}` : cur + acc
);
} |
末尾再reverse一下
…---原始邮件---
发件人: ***@***.***>
发送时间: 2023年8月24日(周四) 下午3:09
收件人: ***@***.***>;
抄送: ***@***.******@***.***>;
主题: Re: [Advanced-Frontend/Daily-Interview-Question] 第 143 题:将'10000000000'形式的字符串,以每3位进行分隔展示'10.000.000.000',多种实现方式 (#296)
function format(str) { return str .split('') .reverse() .reduce((acc, cur, index) => index % 3 === 0 ? `${cur}.${acc}` : `${cur}${acc}` ); }
—
Reply to this email directly, view it on GitHub, or unsubscribe.
You are receiving this because you commented.Message ID: ***@***.***>
|
递归 |
No description provided.
The text was updated successfully, but these errors were encountered: