PDA

View Full Version : جدا كردن رقمها



tux-world
شنبه 01 بهمن 1390, 13:08 عصر
سلام. يه كدي ميخوام داشته باشم كه مثلا كسي خواست نمره اي بده مثلا 12/5 براي يه درس. 125 تايپ كنه و مميز نزنه برنامه خودش ببينه اگه 3 رقم به بالا بود دو رقم از سمت چپ جدا كنه و مميز بزنه براش. من اين كدها رو پيدا كردم ولي نتونستم ازشون استفاده كنم:
NumberFormat.js:

/*
Author: Robert Hashemian
http://www.hashemian.com/

You can use this code in any manner so long as the author's
name, Web address and this disclaimer is kept intact.
************************************************** ******
Usage Sample:

<script language="JavaScript" src="http://www.hashemian.com/js/NumberFormat.js"></script>
<script language="JavaScript">
document.write(FormatNumberBy3("1234512345.12345", ".", ","));
</script>
*/

// function to format a number with separators. returns formatted number.
// num - the number to be formatted
// decpoint - the decimal point character. if skipped, "." is used
// sep - the separator character. if skipped, "," is used
function FormatNumber(id1,id2)
{
document.getElementById(id2).value = FormatNumberBy3(document.getElementById(id1).value );
}
function FormatNumberBy3(num, decpoint, sep) {
// check for missing parameters and use defaults if so
if (arguments.length == 2) {
sep = ",";
}
if (arguments.length == 1) {
sep = ",";
decpoint = ".";
}
// need a string for operations
num = num.toString();
// separate the whole number and the fraction if possible
a = num.split(decpoint);
x = a[0]; // decimal
y = a[1]; // fraction
z = "";


if (typeof(x) != "undefined") {
// reverse the digits. regexp works from left to right.
for (i=x.length-1;i>=0;i--)
z += x.charAt(i);
// add seperators. but undo the trailing one, if there
z = z.replace(/(\d{3})/g, "$1" + sep);
if (z.slice(-sep.length) == sep)
z = z.slice(0, -sep.length);
x = "";
// reverse again to get back the number
for (i=z.length-1;i>=0;i--)
x += z.charAt(i);
// add the fraction back in, if it was there
if (typeof(y) != "undefined" && y.length > 0)
x += decpoint + y;
}
return x;
}

كد HTML:

<script type="text/javascript" src="NumberFormat.js"></script>
<script type="text/javascript" src="jquery.min.js"></script>

<script type='text/javascript'>
$(document).ready(function(){
$('#price2').change( function() {
$(this).val( number_format( $(this).val(), 2, '.', '.' ) );
}
});
</script>
<input type="text" id="price2" />
البته ميشه تعداد كاراكترها رو با تابع change تشخيص داد ولي يه تابع كامل ميخواستم براي همين تاپيك زدم

plague
شنبه 01 بهمن 1390, 23:23 عصر
این تابع هر 3 رقم یدونه کاما میزاره یکم دستکاریش کنی میتونی کاری کنی که هر دو رقم یدونه / بزاره

function addCommas(nStr){

nStr = nStr + '';

nStr = nStr.replace( /\,/g, "");

var x = nStr.split( '.' );

var x1 = x[0];

var x2 = x.length > 1 ? '.' + x[1] : '';

var rgx = /(\d+)(\d{3})/;

while ( rgx.test(x1) ) {

x1 = x1.replace( rgx, '$1' + ',' + '$2' );

}

return x1 + x2;

}