简体   繁体   English

当.toFixed(2)在小数点后给出零时,如何将浮点数格式化为整数?

[英]How to format a float as integer when .toFixed(2) gives zeros after the decimal point?

I wonder what would be the shortest and safest way to achieve the following: 我想知道实现以下目标的最短,最安全的方法是什么:

Suppose I have a float var with the value 1.200123 . 假设我有一个值为1.200123的float var。 In our visualization, I want to show this value with two decimal places, so I use myFloat.toFixed(2); 在我们的可视化中,我想用两位小数显示该值,所以我使用myFloat.toFixed(2); at the moment, which gives me 1.20 . 目前,这给了我1.20

That's fine. 没关系。 But what if the resulting output only has zeros at the decimal places? 但是,如果结果输出的小数位只有零,该怎么办? For example the value 1.000043 which becomes 1.00 . 例如,值1.000043变为1.00

For the case above: how can I omit the decimal point and the zeros and just get 1 as output, preferrably without parsing and manipulating the string that comes out of .toFixed(2) ? 对于上述情况:如何省略小数点和零,而只得到1作为输出,最好不分析和处理.toFixed(2)的字符串?

...preferrably without parsing and manipulating the string that comes out of .toFixed(2)? ...最好不要解析和处理.toFixed(2)产生的字符串?

Well, you could do it numerically, though I'd worry about getting a perfect match between numeric logic and toFixed 's logic , given the definition of toFixed includes phrases like: 好吧,尽管我担心数字逻辑和toFixed的逻辑之间会完美匹配,但考虑到toFixed的定义包括类似以下内容的短语,您可以通过数字方式实现:

Let n be an integer for which the exact mathematical value of n ÷ 10 f - x is as close to zero as possible. n为整数,其精确的数学值n ÷10 f - x尽可能接近零。 If there are two such n , pick the larger n . 如果有两个这样的n ,则选择较大的n

So I'd probably just update the string, it's not a lot of work: 所以我可能只是更新字符串,这不是很多工作:

 function formatNumber(num) { return num.toFixed(2).replace(/\\.00$/, ""); } function test(num) { console.log(num, "=>", formatNumber(num)); } test(1.01); test(1.43); test(23.7); test(1.200123); test(1.000043); test(1.007); test(1.0007); 

But here's an approximate numeric approach, which at least matches the results for the test cases above: 但这是一种近似的数值方法,至少与上述测试用例的结果匹配:

 function formatNumber(num) { var check = Math.round(num * 100) / 100; var rounded = Math.round(check); if (rounded == check) { return String(rounded); } return num.toFixed(2); } function formatNumberViaToFixed(num) { return num.toFixed(2).replace(/\\.00$/, ""); } function test(num) { var formatted = formatNumber(num); var viaToFixed = formatNumberViaToFixed(num); if (formatted == viaToFixed) { console.log(num, "=>", formatted); } else { console.log(num, "=>", formatted, "ERROR: Should be", viaToFixed); } } test(1.01); test(1.43); test(23.7); test(1.200123); test(1.000043); test(1.007); test(1.0007); 
 .as-console-wrapper { max-height: 100% !important; } 

I would create this conditional toFixed method within the Number prototype, which in the end will call the this.toFixed method so that you will keep that original behavior and only adjust the amount of digits passed to it - that can be easily done with Math.pow and Math.trunc . 我将在Number原型中创建此条件toFixed方法,最后将调用this.toFixed方法,以便您将保留原始行为并仅调整传递给它的位数-这可以通过Math.pow轻松完成Math.powMath.trunc

 Object.defineProperty(Number.prototype, 'toConditionalFixed', { enumerable: false, writable: false, configurable: false, value: function(digits) { let comp = Math.pow(10, digits); return this.toFixed(Math.trunc(this * comp) % comp === 0 ? 0 : digits); } }); console.log( (1.200123).toConditionalFixed(2), '|', (1.200123).toConditionalFixed(3), '|', (1.200123).toConditionalFixed(4), '|', (1.000043).toConditionalFixed(2), '|', (1.000043).toConditionalFixed(3), '|', (1.000043).toConditionalFixed(4), '|', (1.000043).toConditionalFixed(5) ); 

EDIT 编辑

For the sake of completeness, the same method within Number.prototype which works with RegExp: 为了完整起见, Number.prototype中与RegExp一起使用的相同方法:

 Object.defineProperty(Number.prototype, 'toConditionalFixed', { enumerable: false, writable: false, configurable: false, value: function(digits) { let re = new RegExp("\\\\." + "0".repeat(digits) + "$"); return this.toFixed(digits).replace(re, ""); } }); console.log( (1.200123).toConditionalFixed(2), '|', (1.200123).toConditionalFixed(3), '|', (1.200123).toConditionalFixed(4), '|', (1.000043).toConditionalFixed(2), '|', (1.000043).toConditionalFixed(3), '|', (1.000043).toConditionalFixed(4), '|', (1.000043).toConditionalFixed(5) ); 

You could use Number(myFloat.toFixed(2)) . 您可以使用Number(myFloat.toFixed(2))

While this produces a value with type number rather than string , you can use it in a string expression (implicitly calling its .toString() method), or call .toString() explicitly, to produce the string format you want. 尽管这会产生类型number而不是string的值,但是您可以在字符串表达式中使用它(隐式调用其.toString()方法),也可以显式调用.toString()以产生所需的字符串格式。

As Number.toString() does no special formatting, converting the string to a number and then back removes trailing zeroes from rounded value produced by .toFixed() . 由于Number.toString()没有特殊格式,因此将字符串转换为数字,然后返回以从.toFixed()产生的舍入值中删除尾随零。

The downside of this method would be that it converts 1.10 to "1.1" rather than "1.10" , which may or may not be what you want for your visualisation. 该方法的缺点是它将1.10转换为"1.1"而不是"1.10" ,这可能是也可能不是您想要的可视化效果。

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

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