如何使答案只有2位小数 [英] How to make the answeer only 2 decimal places

查看:79
本文介绍了如何使答案只有2位小数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码完美无缺,但我需要让第三个文本框限制2个小数位的答案。我试图插入toFixed值,但我似乎无法找到插入它的正确方法。

我的文本框2在其html代码中有onblur =Calculate()以便它触发文本框3输入的计算,但是我得到的小数位数太多。



Here is my code that works perfect except I need to have the third textbox limit the answer to 2 decimal places. I have tried to insert the toFixed value but I can't seem to find the right way to insert it.
My textbox 2 has the onblur="Calculate()" in its html code so that it triggers the calculation for the textbox 3 input but I get too many decimal places.

function Calculate() {
            var t1 = parseFloat(document.getElementById('<%= TextBoxTotalScoreAnc.ClientID%>').value);
            var t2 = parseFloat(document.getElementById('<%= TextBoxPossibleScoreAnc.ClientID%>').value);

           document.getElementById('<%= TextBoxOverallScoreAnc.ClientID%>').value = t1 / t2 * 100 + '%';
        }

推荐答案

请参阅:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/ toFixed [ ^ ],

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toPrecision [ ^ ]。



现在,给你一个很大的警告:避免使用 Math.round 。在99.9999(9?)%的情况下,除了屏幕上显示的最终字符串外,您不需要在任何地方进行舍入。同时,由于某种原因,您可以在某些中间结果上使用舍入,并在最终结果中获得严重的精度损失。这是一些初学者的典型错误。



-SA
Please see:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed[^],
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toPrecision[^].

Now, a big warning for you: avoid using Math.round. In 99.9999(9?)% of the cases, you don't need rounding anywhere except the final string you show on screen. At the same time, you can, by some reason, use rounding on some intermediate results, and get critical precision loss in final results. This is a typical mistake of some beginners.

—SA


相反我使用 .toFixed() [ ^ ]方法。

Rather I'd use .toFixed()[^] method from jQuery.
var n = 2.5689;
alert(n.toFixed(2));
//ouput 2.56





-KR



-KR


这篇关于如何使答案只有2位小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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