简体   繁体   English

JS十进制数问题需要一个类似于toFixed()的function

[英]JS decimal number problem need a function similar to toFixed()

var num = 20.3698  //20.37
var num = 0.36587  //0.37
var num = 0.000014247 //0.000014
var num = 0.0000000000099879 //0.000000000001

I am facing a problem in my JavaScript code: I have some random large and small decimal numbers which on printing takes too much space on view pane.我在 JavaScript 代码中遇到问题:我有一些随机的大小十进制数,打印时在视图窗格上占用了太多空间。

Example: var num = 0.023810002044 is okay because here I can use toFixed(2) but numbers like this 0.00000000008824721 take much space and if I use toFixed(2) then it will give me 0.00 but I want 0.00000000009 and if given a number like 0.03248 then output should be 0.03.示例: var num = 0.023810002044没问题,因为在这里我可以使用toFixed(2)但是像这样的数字 0.00000000008824721 会占用很多空间,如果我使用toFixed(2)那么它会给我 0.00 但我想要 0.00000000009 如果给定一个像 0.03248 这样的数字那么 output 应该是 0.03。

You could take the logarithm of 10 and adjust smaller numbers.您可以取 10 的对数并调整较小的数字。

 const fix = v => v > 0.01? v.toFixed(2): v.toFixed(1 - Math.floor(Math.log10(Math.abs(v)))); console.log([20.3698, 0.36587, 0.000014247, 0.00000000008824721, 0.0000000000099879].map(fix));

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

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