JavaScript - 保持尾随零

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24889498/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 03:30:42  来源:igfitidea点击:

JavaScript - Keep trailing zeroes

javascriptparsingtrailing

提问by Isadora

I want to parse a string and I used parseFloat(), but it removes all the trailing zeroes. How to prevent this - I need to parse the string exactly - if I have 2.5000, I need exactly the same result as a floating-point number - 2.5000.

我想解析一个字符串并使用了parseFloat(),但它删除了所有尾随零。如何防止这种情况 - 我需要准确地解析字符串 - 如果我有 2.5000,我需要与浮点数完全相同的结果 - 2.5000。

回答by Chad Scira

You can do

你可以做

parseFloat(2.5).toFixed(4);

If you need exactly the same floating point you may have to figure out the amount

如果您需要完全相同的浮点数,则可能需要计算出数量

var string = '2.54355';
parseFloat(string).toFixed(string.split('.')[1].length);

But i don't really understand why you even need to use parseFloat then? Numbers in javascript do not retain the floating-point count. so you would have to keep them as strings, and calculate against them as floats.

但我真的不明白为什么你甚至需要使用 parseFloat 呢?javascript 中的数字不保留浮点数。所以你必须将它们保留为字符串,并作为浮点数对它们进行计算。