parsefloat的整数和两个小数点-JavaScript
下面我有一个用例,其中数字存储在DB中为十进制(18,2)。尝试读取数据时,具有.00的数字会转换为整数。
使用.tofix(2)将格式从数字更改为字符串。 //如预期。
我如何保留格式。
输入
const x1 = 4000.00;
const x2 = 4000.01;
const y1 = parseFloat((x1).toFixed(2)); // actual: 4000 expected: 4000.00
const y2 = parseFloat((x2).toFixed(2)); // actual: 4000.01 expected: 4000.01
// const y1 = parseFloat((x1).toFixed(2)).toFixed(2); //datatype: actual: string, expected: number
// const y2 = parseFloat((x2).toFixed(2)).toFixed(2); //datatype: actual: string, expected: number
console.log(typeof(y1), y1);
console.log(typeof(y2), y2);
Below i have a use case, where a number is stored in db as decimal(18, 2). When trying to read the data, the numbers with .00 are converted to integer.
Using .toFixed(2) changes the format from number to string. // as expected.
How can i retain the format.
Input
const x1 = 4000.00;
const x2 = 4000.01;
const y1 = parseFloat((x1).toFixed(2)); // actual: 4000 expected: 4000.00
const y2 = parseFloat((x2).toFixed(2)); // actual: 4000.01 expected: 4000.01
// const y1 = parseFloat((x1).toFixed(2)).toFixed(2); //datatype: actual: string, expected: number
// const y2 = parseFloat((x2).toFixed(2)).toFixed(2); //datatype: actual: string, expected: number
console.log(typeof(y1), y1);
console.log(typeof(y2), y2);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
十进制(18,2)
是一种固定过度编号格式,在这里表示“ 18个十进制数字,其中2个位于小数点的右侧”。通常存储为包装的小数或整数。具有编程语言维护的精度和规模。JavaScript号码不是那样的。它们是IEEE 754双精度二进制浮点数:它们具有浮动十进制(二进制)点,范围的交易精度。
您需要阅读每个程序员对浮点算术的了解或为什么不知道我的数字为什么加起来? 。
decimal(18,2)
is a fixed-precision number format, here meaning "18 decimal digit, with 2 of them to the right of the decimal point". Typically stored as either packed decimal or an integer. with precision and scale maintained by the programming language.Javascript numbers are not like that. They are IEEE 754 double-precision binary floating point numbers: they have a floating decimal (binary) point, and trade precision for range.
You need to read What Every Programmer Should Know About Floating-Point Arithmetic, or Why don’t my numbers add up?.