พบกับบทความเกี่ยวกับคอมพิวเตอร์และ programming ได้ที่ http://articles.modoeye.com | บล็อกอาหาร
Javascript development / จุดทศนิยม 2 ตำแหน่งครับ
kas
kas
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>

kas
kas
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>

webmaster
webmaster
Wed 19 Dec 2007 10:42:50
ProPrice = Number(text2.value) * Number(text1.value);
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 มาใช้งานเอง ซึ่งแต่ก่อนเคยเขียนไว้แต่จำไม่ได้ว่าเอาไว้ไหนแล้ว :)
webmaster
webmaster
Wed 19 Dec 2007 14:17:59
เพิ่มเติมครับ ผมเขียนบทความแก้ปัญหาไว้ที่ http://articles.modoeye.com/Design%20and%20Development/Javascript/toFixed()%20Floating%20point%20error.html
Reply
Name:
E-mail:
Home | Services | Forum | Classified | Directories | Support | Contact
ATOM feed RSS 0.9 feed RSS 1.0 feed RSS 2.0 feed
Copyright © 2005 - 2007 Modoeye.com, All Rights Reserved.
Disclaimer | Privacy policy | Term of Use | Term of Services
Valid XHTML Valid CSS! PHP: Hypertext Preprocessor MySQL database Apache Powered! FreeBSD Power to serve
Modoeye Sitemap Client login