简体   繁体   English

如何在javascript中将数字转换为带有8位小数位的浮点数

[英]how to convert a number to float with 8 point decimal places in javascript

How can i convert a number, a input from my test case which will be of either integer or float, into a float/string number of always with 8 decimal places?我如何将一个数字(来自我的测试用例的输入(整数或浮点数))转换为始终具有 8 个小数位的浮点数/字符串数? say for example, if my input is 3, then i should convert into '3.00000000', if my input is 53.678, then i should convert into '53.67800000'.比如说,如果我的输入是 3,那么我应该转换成 '3.00000000',如果我的输入是 53.678,那么我应该转换成 '53.67800000'。 I have googled and tried with few conversion types like parsing, toPrecision() but could not convert it.我用谷歌搜索并尝试了几种转换类型,如解析、toPrecision(),但无法转换它。 Any help is much appreciated.任何帮助深表感谢。

expect(a).to.equal(b) // a and be should be of same number with types too
expect(a).to.equal(b)

In JavaScript, Number is a double-precision float.在 JavaScript 中, Number一个双精度浮点数。
Its precision cannot be expressed in decimal places , it varies depending on how big the number is.它的精度不能用小数表示,它取决于数字的大小。 Above Number.MAX_SAFE_INTEGER , for example, the precision is "less than 0 decimal places":以上Number.MAX_SAFE_INTEGER为例,精度为“小于 0 位小数”:

 const large = 9007199254740992; const larger = large + 1; console.log(large === larger);

To convert a Number to a String with a fixed number of decimal places, use .toFixed() , as @epascarello suggested:于转换NumberString具有固定小数位数,使用.toFixed()为@epascarello建议:

 const input = 3; const str = input.toFixed(8); console.log(str);

As for doing financial calculations, some say you should never use IEEE 754 floats (such as JavaScript's Number s), although many of the largest companies in finance do just that.至于进行财务计算,有人说您永远不应该使用 IEEE 754 浮点数(例如 JavaScript 的Number s),尽管许多最大的金融公司都这样做了。
To be on the safe side, use a bignum library such as big.js .为了安全起见,请使用bignum库,例如big.js

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM