我有以下虚拟测试脚本:
function test() {
var x = 0.1 * 0.2;
document.write(x);
}
test();Run Code Online (Sandbox Code Playgroud)
这将打印结果0.020000000000000004,只应打印0.02(如果您使用计算器).据我所知,这是由于浮点乘法精度的误差.
有没有人有一个很好的解决方案,以便在这种情况下,我得到正确的结果0.02?我知道有类似的功能toFixed或舍入将是另一种可能性,但我想真正打印整个数字没有任何切割和舍入.只是想知道你们其中一个人是否有一些漂亮,优雅的解决方案.
当然,否则我会转到大约10位左右.
假设我的值为15.7784514,我希望将其显示为15.77而不进行舍入.
var num = parseFloat(15.7784514);
document.write(num.toFixed(1)+"<br />");
document.write(num.toFixed(2)+"<br />");
document.write(num.toFixed(3)+"<br />");
document.write(num.toFixed(10));
Run Code Online (Sandbox Code Playgroud)
结果是 -
15.8
15.78
15.778
15.7784514000
Run Code Online (Sandbox Code Playgroud)
我如何显示15.77?
我正在使用javascript绑定到一些复选框,而toFixed(2)不是四舍五入.任何想法为什么它不四舍五入?例如,如果数字是859.385仅显示859.38而不是859.39.
我还读过,toFixed根据您使用的浏览器,可以进行不同的循环,任何人都知道如何解决这个问题,以便我的javascript计算与我的php计算相匹配?
var standardprice = parseFloat($('#hsprice_'+this.id.split('_')[1]).val());
var price = parseFloat($('#hprice_'+this.id.split('_')[1]).val());
var discount = parseFloat($('#hdiscount_'+this.id.split('_')[1]).val());
var deposit = parseFloat($('#hdeposit_'+this.id.split('_')[1]).val());
var currSprice = parseFloat($('#hTotalSprice').val());
var currPrice = parseFloat($('#hTotalPrice').val());
var currDiscount = parseFloat($('#hTotalDiscount').val());
var currDeposit = parseFloat($('#hTotalDeposit').val());
currSprice += standardprice;
currPrice += price;
currDiscount += discount;
currDeposit += deposit;
$('#lblTotalSprice').text('$'+addCommas(currSprice.toFixed(2)));
$('#lblTotalPrice').text('$'+addCommas(currPrice.toFixed(2)));
$('#lblTotalDiscount').text('$'+addCommas(currDiscount.toFixed(2)));
$('#lblTotalDeposit').text('$'+addCommas(currDeposit.toFixed(2)));
$('#hTotalSprice').val(currSprice.toFixed(2));
$('#hTotalPrice').val(currPrice.toFixed(2));
$('#hTotalDiscount').val(currDiscount.toFixed(2));
$('#hTotalDeposit').val(currDeposit.toFixed(2));
Run Code Online (Sandbox Code Playgroud) 是否有一个用于JavaScript或内置的bignum库,我可以包括
<script type="text/javascript" src="the_bignum_library.js"></script>
Run Code Online (Sandbox Code Playgroud)
?
我认为我的用户更愿意在网页中输入数字并等待7秒才能获得结果,而不是下载可执行文件并点击一堆"此可执行文件可能会损害您的计算机"警告屏幕进行安装.
我考虑过自己的http://github.com/silentmatt/javascript-biginteger或http://www.mainebrook.com/john/fun/euler.html.或者你会建议从JavaScript调用Java bignum库,如apfloat?
我有一个字符串,例如:"4.874915326E7".将其转换为javascript数字格式的最佳方法是什么?(int还是float)?如果我尝试parseInt(),则忽略末尾的E.
我想要的是与Number.prototype.toPrecision()几乎相反,这意味着当我有数字时,它有多少小数?例如
(12.3456).getDecimals() // 4
Run Code Online (Sandbox Code Playgroud) 我想创建一个输入值并将其转换为科学记数法的函数(N x 10 ^ a)
我尝试了很多不同的东西,但我似乎无法做到.
例:
我输入200.转换器将其转换为2 x 10 ^ 2
我正在寻找一个处理真实(长,大,巨大,风暴)数字的数学解决方案.我还没有找到任何东西,但我不想认为这个问题目前还没有解决.我正在寻找一个简单的数字解决方案,如Microsoft Excel Precision(30位小数)或BigInteger(Java)解决方案.在Javascript当然.
当我想选择第n个字符时,我使用charAt()方法,但在处理整数而不是字符串值时,我可以使用什么?
这个问题不是寻求开发人员代码格式化意见.就个人而言,我更喜欢在我的JS代码中使用科学记数法,因为我相信它更具可读性.对我来说,6e8更具可读性600000000.话虽这么说,我只是在寻找JS中用科学记数法指定数字的潜在风险和缺点.我不经常在野外看到它,并且想知道是否有技术推理,或仅仅是因为开发人员的笨蛋.