问题描述
我想解析一个字符串,我使用 parseFloat()
,但它删除了所有尾随的零。如何防止这种情况 - 我需要准确地解析字符串 - 如果我有2.5000,我需要与浮点数完全相同的结果 - 2.5000。
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.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);
但我真的不明白为什么你甚至需要使用parseFloat呢? javascript中的数字不保留浮点数。所以你必须将它们保存为字符串,并将它们计算为浮点数。
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.
这篇关于JavaScript - 保持尾随零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!