将尾随零添加到整数而不转换为JS中的字符串?

2022-01-17 00:00:00 numbers javascript

我希望在整数末尾添加小数.举个例子:

I'm looking to add decimals to the end of my integer. As an example:

15 => 15.00

15 => 15.00

toFixed 等方法的问题在于它会将其转换为字符串.我尝试在字符串上使用 parseFloat() 和 Number(),但它会将其转换回没有小数的整数.

The problem with methods like toFixed is that it will convert it into a string. I've tried to use parseFloat() and Number() on the string, but it'll convert it back to an integer with no decimals.

这可能吗?如果不是,有人可以向我解释为什么这是不可能的背后的逻辑吗?

Is this possible? If not, can someone explain to me the logic behind why this isn't possible?

Welp 的意图是将数字显示为数字,但从目前的共识来看,似乎唯一的方法是使用字符串.找到了原因的答案:https://stackoverflow.com/a/17811916/8869701

Welp the intent was to display the number as a number, but from the going consensus, it looks like the way the only way to go about it is to use a string. Found an answer on the why: https://stackoverflow.com/a/17811916/8869701

推荐答案

您发现的问题是javascript中的所有数字都是浮点数.

The problem you are finding is that all numbers in javascript are floats.

a = 0.1
typeof a # "number"

b = 1
typeof b # number

它们是一样的.

所以没有真正的方法可以将整数转换为浮点数.

So there is no real way to convert to from an integer to a float.

这就是所有 parseFloat 等都是用于从字符串中读取和写入数字的字符串方法的原因.即使你确实有浮点数和整数,指定一个数字的精度只有在你向用户显示它时才真正有意义,为此它无论如何都会被转换为字符串.

This is the reason that all of the parseFloat etc are string methods for reading and writing numbers from strings. Even if you did have floats and integers, specifying the precision of a number only really makes sense when you are displaying it to a user, and for this purpose it will be converted to a string anyway.

根据您的具体用例,如果您想以定义的精度显示,则需要使用字符串.

Depending on your exact use case you will need to use strings if you want to display with a defined precision.

相关文章