I used the link below for convert Jalali to Gregorian:
https://github.com/Mds92/MD.BootstrapPersianDateTimePicker/tree/master/MD.BootstrapPersianDateTimePicker/Scripts
I receive data from user as string.
And this is the code I use:
<script>
var jj = document.getElementById("fromDate1"),
bb = document.getElementById("showMe"),
splitOb, yy, mm, dd;
bb.onclick = function () {
splitOb = jj.value.split("/");
for (var i = 0; i < splitOb.length; i++) {
yy = splitOb[0];
mm = splitOb[1];
dd = splitOb[2];
}
var xx = yy.trim().toString(), nn = mm.trim().toString(), mmm = dd.trim().toString();
var xxx = parseInt(xx, 10);
var nnn = parseInt(nn, 10);
var mjj = parseInt(mmm, 10);
var hello = toGregorian(xxx, nnn, mjj);
alert(hello.gy + "/" + hello.gm + "/" + hello.gd);
/* var gh= "1395";
var ghh = parseInt(gh);
alert(ghh);*/
};
</script>
I used parseInt in my code and unfortunately the result is Nan, I checked my variables, all of them was strings. But when I convert them from string to integer the result is NaN too.
when I set string to my variables manually like this code:
var jjj = "1395";
var yyyt = "05";
var kik = "04";
var xxx = parseInt(jjj, 10);
var nnn = parseInt(yyyt, 10);
var mjj = parseInt(kik, 10);
var hello = toGregorian(xxx, nnn, mjj);
alert(hello.gy + "/" + hello.gm + "/" + hello.gd);
Everything works fine, why?
NaN means Not A Number. Maybe you could eliminate that toString() part.
<script>
var jj = document.getElementById("fromDate1"),
bb = document.getElementById("showMe"),
splitOb, yy, mm, dd;
bb.onclick = function () {
splitOb = jj.value.split("/");
for (var i = 0; i < splitOb.length; i++) {
yy = splitOb[0];
mm = splitOb[1];
dd = splitOb[2];
}
var xxx = parseInt(yy, 10);
var nnn = parseInt(mm, 10);
var mjj = parseInt(dd, 10);
var hello = toGregorian(xxx, nnn, mjj);
alert(hello.gy + "/" + hello.gm + "/" + hello.gd);
/* var gh= "1395";
var ghh = parseInt(gh);
alert(ghh);*/
};
</script>
This could help answer your question. It seems that it's unable to convert the first character or some of the characters to a numerical value. That's what is causing the issue.
I GOT IT !!
The problem was that the string that I get form users was Persian/Arabic. I should change it to English string numbers. I used this code to solve the problem:
function parseArabic(str) {
return Number( str.replace(/[٠١٢٣٤٥٦٧٨٩]/g, function(d) {
return d.charCodeAt(0) - 1632;
}).replace(/[۰۱۲۳۴۵۶۷۸۹]/g, function(d) {
return d.charCodeAt(0) - 1776;
}) );
}
I would be appreciate if you have another customized code to tell me.
Thanks for your consideration.
Related
I have a JS counter which is working perfectly, but I want to restrict it to two numbers after the decimal point. Right now it can go as high as 9. Any ideas for solutions which won't mess up the rest of the code?
Here's a JSFiddle with my code, also listed below: https://jsfiddle.net/nd252525/26pvd7g3/3/
var INTERVAL_FIRST = 1;
var INCREMENT_FIRST = 0.86;
var START_VALUE_FIRST = 12574343;
var COUNT_FIRST = 0;
window.onload = function () {
var msInterval2 = INTERVAL_FIRST * 1000;
var NOW_FIRST = new Date();
COUNT_FIRST =
parseInt((NOW_FIRST - START_DATE) / msInterval2) * INCREMENT_FIRST +
START_VALUE_FIRST;
document.getElementById("first-ticker").innerHTML = addCommas(COUNT_FIRST);
setInterval(
"COUNT_FIRST += INCREMENT_FIRST; document.getElementById('first-ticker').innerHTML = addCommas(COUNT_FIRST);",
msInterval2
);
};
function addCommas(nStr) {
nStr += "";
x = nStr.split(".");
x1 = x[0];
x2 = x.length > 1 ? "." + x[1] : "";
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, "$1" + "," + "$2");
}
return x1 + x2;
}
Any help is greatly appreciated, thanks :)
You can apply the .toFixed(2) method to your COUNT_FIRST variable to restrict it to 2 digits after the decimal point.
Your code will look like this:
window.onload = function () {
var msInterval2 = INTERVAL_FIRST * 1000;
var NOW_FIRST = new Date();
COUNT_FIRST =
parseInt((NOW_FIRST - START_DATE) / msInterval2) * INCREMENT_FIRST +
START_VALUE_FIRST;
// Add one here
document.getElementById("first-ticker").innerHTML = addCommas(COUNT_FIRST.toFixed(2));
// And one more here
setInterval(
"COUNT_FIRST += INCREMENT_FIRST; document.getElementById('first-ticker').innerHTML = addCommas(COUNT_FIRST.toFixed(2));",
msInterval2
);
};
The code was tested with your provided JSFiddle.
How to set auto 2 decimal number using value from id input type="text" javascript ?
http://jsfiddle.net/A4wxX/90/
First , fill data eg: 2 into input , it's will update input to 2.00
But not work When i user this
var numb = document.getElementById("int").value;
How can i do ? thank.
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script type="text/javascript">
function fn_do() {
var numb = document.getElementById("int").value;
//var numb = 123;
var zzz = numb.toFixed(2);
document.getElementById("int").value = zzz;
}
</script>
<input type="text" id="int" onchange="fn_do()">
You should use parseFloat, because DOM property value is a string, not number.
var zzz = parseFloat(numb).toFixed(2)
And don't use parseInt, because it'll give you an integer, for example parseInt("1.2") will be 1, then toFixed(2) gives you 1.00, while you actually want 1.20 I assume.
One more thing to care is, make sure input content is valid, for example parseFloat('qwer') will give you NaN. So the final code would look like:
var zzz = (parseFloat(numb) || 0).toFixed(2);
Instead of
var zzz = numb.toFixed(2)
Try
var zzz = parseFloat(numb).toFixed(2) //use parseInt() or parsFloat() as shown here.
Your complete will look like this :-
function fn_do() {
var numb = document.getElementById("int").value;
var zz = parseFloat(numb) || 0; //it will convert numb to float if conversion fails it will return 0.
var zzz = zz.toFixed(2);
document.getElementById("int").value = zzz;
}
Fiddle
var decimalForm = parseFloat(Math.round( intNum * 100) / 100).toFixed(2);
alert(decimalForm );
If I'm understanding this correctly, you want whatever number is put into the object with the id 'int' to be automatically converted to a decimal value with two placeholders. You could do something like this:
function convertToDecimal(value) {
var tempValue = Nath.Round(parseFloat(value) * 100);
var returnValue = tempValue * .01;
return returnValue;
}
That would ensure that you always get two decimal places
Exceptions: 1. if tempValue is a multiple of 10, only one decimal will come out
2. if tempValue is a multiple of 100, no decimals will be returned
Solution:
function convertDecimals(convertedValue) {
var tempValue = Nath.Round(parseFloat(value) * 100);
if ((tempValue % 10) == 0) {
if ((tempValue % 100) == 0) { var returnValue = convertedValue + .00; return returnValue; } else {
var returnValue = convertedValue + 0;
return returnValue;
}
}
return '';
}
So maybe the whole cde would look like this
function fn_do() {
var numb = document.getElementById("int").value;
//var numb = 123;
var zzz = convertToDecimal(numb);
zzz = zzz + convertDecimal(zzz);
document.getElementById("int").value = zzz;
}
function convertToDecimal(value) {
var tempValue = Nath.Round(parseFloat(value) * 100);
var returnValue = tempValue * .01;
return returnValue;
}
function convertDecimals(convertedValue) {
var tempValue = Nath.Round(parseFloat(value) * 100);
if ((tempValue % 10) == 0) {
if ((tempValue % 100) == 0) { var returnValue = convertedValue + .00; return returnValue; } else {
var returnValue = convertedValue + 0;
return returnValue;
}
}
return '';
}
im trying to display the 2 decimal point of the 2 total number and minus them but it didnt compute the decimal point. anyone would like to figure this out. thanks.
function calculate() {
var myBox1 = document.getElementById('box1').value;
var myBox2 = document.getElementById('box2').value;
var basicpay = document.getElementById('basicpay');
var myResult = myBox1 * myBox2;
basicpay.value = myResult.toFixed(2);
document.getElementById('both').value = sum() - diff();
}
this is the diff part
function diff() {
var absent = document.getElementById('absent').value;
var tardiness = document.getElementById('tardiness').value;
var sss = document.getElementById('sss').value;
var pagibig = document.getElementById('pagibig').value;
var philhealth = document.getElementById('philhealth').value;
var cashadvances = document.getElementById('cashadvances').value;
var withholdingtax = document.getElementById('withholdingtax').value;
var others = document.getElementById('others').value;
var result =
parseInt(absent) +
parseInt(tardiness) +
parseInt(sss) +
parseInt(pagibig) +
parseInt(philhealth) +
parseInt(cashadvances) +
parseInt(withholdingtax) +
parseInt(others) || 0;
if (!isNaN(result)) {
document.getElementById('totaldeductions').value = result.toFixed(2);
return result;
}
}
this is the sum part
function sum() {
var basicpay = document.getElementById('basicpay').value;
var overtime = document.getElementById('overtime').value;
var regularholiday = document.getElementById('regularholiday').value;
var specialholiday = document.getElementById('specialholiday').value;
var allowanceday = document.getElementById('allowanceday').value;
var monthpay = document.getElementById('monthpay').value;
var others1 = document.getElementById('others1').value;
var result =
parseInt(basicpay) +
parseInt(overtime) +
parseInt(regularholiday) +
parseInt(specialholiday) +
parseInt(allowanceday) +
parseInt(monthpay) +
parseInt(others1) || 0;
if (!isNaN(result)) {
document.getElementById('totalgrosspay').value = result.toFixed(2);
return result;
}
}
In your Sum() and Diff() function, you are working only with integers. Integers are whole numbers only, so will not retain anything after a decimal point. To deal with decimals, you will need to use JavaScript's parseFloat() function. To give an example, in your Sum() function you would change the result calculation to look like the following:
var result =
parseFloat(basicpay) +
parseFloat(overtime) +
parseFloat(regularholiday) +
parseFloat(specialholiday) +
parseFloat(allowanceday) +
parseFloat(monthpay) +
parseFloat(others1) || 0;
This will retain the decimal points in the numbers rather than truncating to whole numbers as the parseInt()
I am trying to format a variable value that contains time data and is like the following 00:38:51 or 00:00:59 or 01:25:59
I need to format it like 25m59s or with hour accordingly 1h25m59s 0m59s
I am doing some reading on splits and I have made a start but I am getting confused.
Syntax
Split(expression[,delimiter[,count[,compare]]])
time = "00:38:51"
timeArray = time.split(":",-1)
document.write(timeArray[0]);
Update
I created my own function, I am not sure if this is a good way to do it also;
function formatTime(a) {
var time = a.split(":");
var hours = parseInt(time[0], 10);
var minutes = parseInt(time[1], 10);
var seconds = parseInt(time[2], 10);
var x = document.getElementById("time");
x.innerHTML = hours + "h" + minutes + "m" + seconds + "s"
}
myTime = "00:38:51";
formatTime(myTime);
http://jsfiddle.net/V64dJ/
Try with RegExp
var arr = ["00:38:51","00:00:59","01:25:59"]; // created array due to demonstration
var reg = /(\d+):(\d+):(\d)/, ret = []; // RegExp and result variable declaration
arr.forEach(function(v){
ret = reg.exec(v);
console.log(parseInt(ret[1]) + "h" + parseInt(ret[2]) + "m" + parseInt(ret[3]) + "s"); // 0h38m5s, 0h0m5s, 1h25m5s
});
JSFiddle
NOTE: Using parseInt function during displaying results due to avoid printing 00 instead of 0
This should do it!
function a(time) {
var t = time.split(':'),
s = ['h', 'm', 's'],
i = 0;
for(; i < t.length; i ++) {
t[i] = parseInt(t[i]) == 0 ? '' : parseInt(t[i]) + s[i + s.length - t.length];
}
return t.join('');
}
Fiddle
In my code I have a variable myCash, which is printed into an h1 element using javaScript's innerHTML. I found a function online that puts a comma after every third character from the end of the number so that the number is easier to read. I've tried for a couple of hours now sending my variable myCash into the function and then print it on the screen. I CANNOT get it to work.
I've tried just alerting the new variable to the screen after page load or by pressing a button, but I get nothing and the alert doesn't even work. Here's the comma insert function:
function commaFormatted(amount) {
var delimiter = ","; // replace comma if desired
amount = new String(amount);
var a = amount.split('.',2)
var d = a[1];
var i = parseInt(a[0]);
if(isNaN(i)) { return ''; }
var minus = '';
if(i < 0) { minus = '-'; }
i = Math.abs(i);
var n = new String(i);
var a = [];
while(n.length > 3)
{
var nn = n.substr(n.length-3);
a.unshift(nn);
n = n.substr(0,n.length-3);
}
if(n.length > 0) { a.unshift(n); }
n = a.join(delimiter);
if(d.length < 1) { amount = n; }
else { amount = n + '.' + d; }
amount = minus + amount;
return amount;
}
now when I want my variable to change I've tried it a few different ways including this:
var newMyCash = commaFormatted(myCash);
alert(newMyCash);
and this:
alert(commaFormatted(myCash);
Where of course myCash equal some large number;
This does absolutely nothing! What am I doing wrong here??
Also,
Try this as a drop in replacement and try alerting the response:
http://phpjs.org/functions/number_format:481
Do you see any errors in the console of your browser (usually f12)?
This is not my function, but I hope it helps you.
function addCommas(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
Usage:
var newMyCash = addCommas( myCash ); alert( newMyCash );
Source: http://www.mredkj.com/javascript/nfbasic.html
You are most likely not passing in a number that contains a decimal, which the function expects.
Working Demo