简体   繁体   English

如何格式化浮点数,最多保留“ n”个小数位而不会尾随零

[英]How to format a float, up to “n” decimal places without trailing zeros

How to format number in JavaScript like c# as 0.#### ? 如何在JavaScript中将数字格式化,例如将c#设置为0。####?

I use function .toFixed(4) but It's format 0.0000 我使用函数.toFixed(4)但格式为0.0000

var x = a / b;
console.log(x.toFixed(4));

I want to format like this... 我想这样格式化...

1.0000 -> 1

1.2000 -> 1.2

1.2300 -> 1.23

1.2340 -> 1.234

1.2345 -> 1.2345

1.23456... -> 1.2346

Combine Number.prototype.toFixed() with a small RegExp replacement Number.prototype.toFixed()与少量RegExp替换结合

console.log(x.toFixed(4).replace(/\.?0+$/, ''))

 const nums = ['1.0000', '1.2000', '1.2300', '1.2340', '1.2345', '1.23456'] const rx = /\\.?0+$/ nums.forEach(num => { console.info(num, ' -> ', parseFloat(num).toFixed(4).replace(rx, '')) }) 

The toFixed() method formats a number using fixed-point notation. toFixed()方法使用定点表示法格式化数字。

toFixed won't give you result in such format, you can change the values after decimal using regex toFixed不会为您提供这种格式的结果,您可以使用正则表达式更改小数点后的值

 let a = 4 let b = 3 let x = ( a / b ).toFixed(4) console.log(x.replace(/\\.(.*)$/g,(match,g1)=>{ return `.${g1 ? '#'.repeat(g1.length) : ''}` })); 

Update 更新

 let a = 4 let b = 3 let changedFormat = (a,b) => { return ( a / b ).toFixed(4).replace(/\\.?0+$/g, '') } console.log(changedFormat(a,b)) console.log(changedFormat(1,1)) console.log(changedFormat(6,4)) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM