将尾随零添加到整数而不在JS中转换为字符串? [英] Add trailing zeros to an integer without converting to string in JS?

查看:30
本文介绍了将尾随零添加到整数而不在JS中转换为字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要在小数末尾添加小数.例如:

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?

意图是将数字显示为数字,但是从目前的共识来看,似乎唯一的处理方法是使用字符串.找到了以下原因的答案: 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.

这篇关于将尾随零添加到整数而不在JS中转换为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆