Add trailing zeros to an integer without converting to string in JS?(将尾随零添加到整数而不转换为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?
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.
这篇关于将尾随零添加到整数而不转换为JS中的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将尾随零添加到整数而不转换为JS中的字符串?
基础教程推荐
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- 直接将值设置为滑块 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01