如何使用JavaScript将浮动数转换为固定的浮动号码

发布于 2025-02-07 03:13:30 字数 229 浏览 1 评论 0 原文

例如,我想计算3/6。 3/6的答案是0.5浮数。当我使用JavaScript Tofix(6)方法修复此数字时,它返回了“ 0.500000”。问题是“ 0.500000”是字符串。但是我想要一个浮点数,其中有6位(。)之后。我该怎么做?我尝试了这个,但它行不通。

parseFloat((3/6).toFixed(6))
//output = 0.5 but i want 0.500000

For example, I want to calculate 3/6. 3/6 answer is a 0.5 floating number. When I fixed this number with the javascript toFixed(6) method it returned '0.500000'. The problem is that '0.500000' is a string. But I want a floating number with 6 digits after the dot(.). How can I do that? I tried this but it's won't work.

parseFloat((3/6).toFixed(6))
//output = 0.5 but i want 0.500000

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

调妓 2025-02-14 03:13:30

好吧,

parseFloat((3/6).toFixed(6))
//output = 0.5 means everything after .5 is 0

如果您将其打印到控制台,它将删除不必要的零。当您需要打印多达5或10个小数点时,必须使用Tofixed方法将数字转换为字符串。

Well,

parseFloat((3/6).toFixed(6))
//output = 0.5 means everything after .5 is 0

If you print it to the console it will remove the unnecessary zero. When you need to print up to 5 or 10 decimal points, you have to convert the number into a string using the toFixed method.

凹づ凸ル 2025-02-14 03:13:30

您为什么在 parsefloat()内使用 tofixed ,因为它正在返回您 0.5

执行此操作

let a = parseFloat((3/6).toFixed(6))
console.log(a)

Why are you using toFixed inside the parseFloat() because of that it is returning you 0.5

Do this

let a = parseFloat((3/6).toFixed(6))
console.log(a)
夏末的微笑 2025-02-14 03:13:30

我更新了答案。我不知道您想将输出用作数字。我认为您想实现的目标是不可能的。只有在将自己的价值作为字符串保持时,才有可能。

const numb = 3/6;
console.log(numb.toFixed(6));

用于文档:

I updated my answer. I did not get that you wanted to use the output as a number. I don't think that what you want to achieve is possible. It's possible only if you keep you value as a string.

const numb = 3/6;
console.log(numb.toFixed(6));

For documentation: https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文