Tue 18 Dec 2007 19:20:03
ช่วยดู Code ให้หน่อยครับ ว่าทำไมถึงไม่ได้ จุดทศนิยม 2 ตำแหน่งครับ
<SCRIPT ID=clientEventHandlersJS LANGUAGE=javascript>
<!--
function isNum(val)
{
if (""+(val-0) == "NaN") return false;
return true;
}
function button1_onclick() {
if ((!isNum(text2.value))||
(!isNum(text1.value))||
(!isNum(text3.value))||
(!isNum(text4.value)))
{
alert("Please fill number !!! ");
return false;
}
ProPrice = new Number(text2.value)*new Number(text1.value)
ProVat = ProPrice*new Number(text3.value)/100
text4.value = Math.round(ProPrice + ProVat)
}
//-->
</SCRIPT>
Tue 18 Dec 2007 20:08:56
<SCRIPT ID=clientEventHandlersJS LANGUAGE=javascript>
<!--
function isNum(val)
{
if (""+(val-0) == "NaN") return false;
return true;
}
function button1_onclick() {
if ((!isNum(text2.value))||
(!isNum(text1.value))||
(!isNum(text3.value))||
(!isNum(text4.value)))
{
alert("Please fill number !!! ");
return false;
}
ProPrice = new Number(text2.value)*new Number(text1.value)
ProVat = ProPrice*new Number(text3.value)/100
text4.value = (Math.round(ProPrice + ProVat)*10/100) <-------แก้ตรงนี้แต่ได้ 1 ตำแหน่ง
}
//-->
</SCRIPT>
Wed 19 Dec 2007 10:42:50
ProVat = ProPrice * (Number(text3.value)/100);
text4.value = Number(ProPrice + ProVat).toFixed(2);
แต่จะมีปัญหาตรง precision error ใน javascript ในหลายๆ browser ซึ่งมีมาหลายปีแล้วยังไม่มีการแก้ไข เช่น
num = 16.295;
alert(num.toFixed(2)); // เอาทศนิยม 2 หลัก
จริงๆควรจะเป็น 16.30 แต่ใน browser ต่างๆจะได้เป็น 16.29 ซึ่งวิธีแก้ก็เขียน function มาใช้งานเอง ซึ่งแต่ก่อนเคยเขียนไว้แต่จำไม่ได้ว่าเอาไว้ไหนแล้ว :)
Wed 19 Dec 2007 14:17:59

















