簡體   English   中英

如何格式化浮點數,最多保留“ n”個小數位而不會尾隨零

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

如何在JavaScript中將數字格式化,例如將c#設置為0。####?

我使用函數.toFixed(4)但格式為0.0000

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

我想這樣格式化...

1.0000 -> 1

1.2000 -> 1.2

1.2300 -> 1.23

1.2340 -> 1.234

1.2345 -> 1.2345

1.23456... -> 1.2346

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, '')) }) 

toFixed()方法使用定點表示法格式化數字。

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) : ''}` })); 

更新

 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