Javascript浮点数乘以100仍然有错误 [英] Javascript Floating Point Multiply by 100 Still has Errors

查看:50
本文介绍了Javascript浮点数乘以100仍然有错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在钱栏上输入了文字.

I have a text input for a money field.

我在字段中输入33.91,并在尝试使用乘以100"技术时得到以下结果.

I enter 33.91 into the field, and get the following results while trying to use the 'multiply by 100' technique.

var curWth = parseInt($('#trans_withdraw'+index).val()*100);   // 3390
var curWth = parseInt($('#trans_withdraw'+index).val())*100;   // 3300  
var curWth = $('#trans_withdraw'+index).val()*100;             // 3390.9999999...5
var curWth = parseFloat($('#trans_withdraw'+index).val())*100; // 3390.9999999...5
var curWth = parseFloat($('#trans_withdraw'+index).val()*100); // 3390.9999999...5

这些都不给我3391.我认为乘以100的整个想法是要摆脱浮点问题.但是,如第3行所示,当我立即将值乘以100时,仍然会出现浮点错误.

None of these give me 3391. I thought the whole idea of multiplying by 100 was to get away from the floating point problem. But as line 3 shows, when I multiply the value by 100 immediately, I still get floating point errors.

在使用货币时,我仍然不了解什么?

What am I still not understanding about working with currency?

我知道0.1不能正确存储为浮点数.但是在这种情况下,乘以100也不适合我.

I know 0.1 can't be stored correctly as a float. But multiplying by 100 is also not working for me in this case.

推荐答案

praseFloat to get your decimal value then multiple by 100 to get 3390.9999 then Math.round() to get the value.

var number = parseFloat($('#trans_withdraw').val()).toFixed(2);
var value = number * 100;

console.log(Math.round(value));

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="trans_withdraw" value="33.91" />

这篇关于Javascript浮点数乘以100仍然有错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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