1 頁 (共 1 頁)

請問javascript 裡如何取道小數點第二位呢

發表於 : 2004-04-15 18:02:48
yehlu
摘錄自
http://www.hkln.net/_discuss/discuss.pl ... g&thid=134

<script>
var v = '12.34567';
alert( roundp(v, 3) );


/*
Round a string to some decimal places
*/
function roundp(v, dp) {
var dotpos; // position of decimal point
var ary = new Array();

// Make sure it has a dot
if ( v.indexOf('.') == -1 ) v += '.';

dotpos = v.indexOf(".");

// Convert string to Array
for (var i = 0 ; i < v.length ; i++) ary = v.charAt(i);

// Append trailing zero if the string is too short
var temp = dotpos + dp - v.length + 1;
for (var i = 0 ; i <= temp ; i++) ary[ary.length] = '0';

// Check if carry is needed after rounding
var carry_flag = false;
if ( ary[dotpos + dp + 1] >= 5 ) carry_flag = true;

// Do carry for other digit
for (var i = dotpos + dp ; i >= 0 && carry_flag ; i--) {
// Skip the dot and pocess the next digit
if (ary == '.') continue;

if (ary != '9') {
ary++;
carry_flag = false;
} else { // 9 + 1 = 10
ary = '0';
carry_flag = true;
}
}

// Check if a new digit is needed after carry
v = (carry_flag)? '1' : '';

// Chop the last digit
ary.length = dotpos + dp + 1;

// Chop the dot if no decimal place
if (dp == 0) ary.length--;

// Convert array into string
for (var i = 0 ; i < ary.length ; i++) v = v + ary;

return v;
}

</script>