I am attempting to make a conditional statement where the code will only run if it is a real number 90 vs a string number "90". I don't know what to type into the number part in my conditional statement. I have tried using Number and I have also tried variations of typeof() method. My code is listed below. Thank you
function sumAll(start, end) {
let x = 0;
array = [];
if (start === Number && end === Number) {
if (start < end && start >= 0) {
for (let i = start; i <= end; i++) {
array.push(i);
console.log(array);
x = i + x;
}
return x;
} else if (start > end) {
for (let i = start; i >= end; i--) {
array.push(i);
// console.log(array);
x = i + x;
}
return x;
} else {
return 'ERROR';
}
} else {
return 'ERROR not a number';
}
}
console.log(sumAll(10, 90));
sumAll(10, "90")
// expect(sumAll(10, "90")).toEqual('ERROR');
```
let n = 5;
console.log(n === Number);
console.log(typeof n === "number");
The first one logs false, the second one true.
You should try using typeof to check if start and end are numbers in your code.
You need to use the typeof operator
Using it, you can check to see if start and end are 'number'
function sumAll(start, end) {
let x = 0;
array = [];
if (typeof start === 'number' && typeof end === 'number') {
if (start < end && start >= 0) {
for (let i = start; i <= end; i++) {
array.push(i);
console.log(array);
x = i + x;
}
return x;
} else if (start > end) {
for (let i = start; i >= end; i--) {
array.push(i);
// console.log(array);
x = i + x;
}
return x;
} else {
return 'ERROR';
}
} else {
return 'ERROR not a number';
}
}
console.log(sumAll(10, 90));
console.log(sumAll(10, "90"));
// expect(sumAll(10, "90")).toEqual('ERROR');}
I think you used typeof wrongly, because that is the answer you need here.
const a = 5;
const b = '5';
if (typeof a === 'number') { } //true
if (typeof a === 'string') { } //false
if (typeof b === 'number') { } //false
if (typeof b === 'string') { } //true
console.log('type of a: ', typeof a);
console.log('type of b: ', typeof b);
But it seems like you can use string '90' as well converting it into number.
function sumAll(start, end) {
let x = 0;
array = [];
if (typeof start === 'string') { start = parseInt(start, 10); } // case '90'
if (typeof end === 'string') { end = parseInt(end, 10); } // case '90'
if (Number.isNaN(start) || Number.isNaN(end)) {
// Error case
return 'Error not a number'; // Throw could be better here though
}
// any operation you need to do is here
// if you need to sum number between start and end its called
// For example summing operation
return end > start
? (end * (end + 1) / 2) - ((start - 1) * start / 2)
: (start* (start + 1) / 2) - ((end- 1) * end / 2)
}
console.log(sumAll(10, 12));
Links: https://github.com/VirxEC/CalcPlus/blob/master/assets/Library.js and https://virxec.github.io/CalcPlus/PreviewLibrary/ these are just links to the main code if needed. The first link is the source, the second is the run environment.
The function expo has a very critical issue. I will explain what it does, then I will explain the exact issue and what I've tried to fix it. So the function is meant to calculate exponents up to 264-1 digits long. (For the answer.) It works by running the multiplication function multiple times (on lines 196-197: final = multi(num1, num1); for (var i="2"; isLessThan(i, num2); i=add({num:i.split(""),isNeg:false,decimals:0}, {num:["1"],isNeg:false,decimals:0})) final = multi(final, num1);)
The objects that you see are passed into the isLessThan() function are examples of me passing pre-parsed numbers to the function doesn't have to re-parse them and take up computer resources. This passing of a pre-parsed object is where the error is. On line 197, you can see final = multi(final, num1); The final variable is not pre-parsed for obvious reasons, but num1 is. However, if you go into the chrome debugger and watch the num1 variable, the multi() function changes the content of the property num1.num from (if you did 264) from ["2"] to ["0","2"] causing and incorrect answer.
I've tested force-removing this behavior is intended for the multi function, but it shouldn't be modifying the argument. I've tried naming the variable something else, using const, and trying to set the object to be read-only nothing has worked. I've even tried something like this:
num1save = num1;
final = multi(num1, num1);
for (var i="2"; isLessThan(i, num2); i=add({num:i.split(""),isNeg:false,decimals:0}, {num:["1"],isNeg:false,decimals:0})) {
final = multi(final, num1);
num1 = num1save;
}
However, somehow, the variable manages to change num1save. Any variable referenced at some point to the object is changed. I have no idea why this is happening. This same thing happens with the isLessThan() function and the variable num2 on line 197.
This includes only the required code, so the lines won't match up:
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
// https://github.com/VirxEC/CalcPlus/blob/master/LICENSE
function parseNums(num1pre, num2pre, mode) {
if (["string", "object"].indexOf(typeof num1pre) == -1) throw new TypeError("The first number wasn't a string (or object). It has to be a string (or object). Note that an object input is ment to submit a pre-parsed number.");
if (["string", "object"].indexOf(typeof num2pre) == -1) throw new TypeError("The second number wasn't a string (or object). It has to be a string (or object). Note that an object input is ment to submit a pre-parsed number.");
if (typeof mode != "number" || [1, 2, 3, 4, 5].indexOf(mode) == -1) throw new TypeError("The mode must be a number from 1-5.");
var num1 = num1pre,
num2 = num2pre,
skip = false,
stringMode1 = true,
stringMode2 = true,
neg = [false, false, false],
decimal = 0,
decimal1 = 0,
decimal2 = 0,
num1pos, num2pos, maxChar, numl;
if (num1.num != undefined) neg[1] = num1pre.isNeg, decimal1 = num1pre.decimals, num1 = num1pre.num, stringMode1 = false;
if (num2.num != undefined) neg[2] = num2pre.isNeg, decimal2 = num2pre.decimals, num2 = num2pre.num, stringMode2 = false;
if (stringMode1 && num1.split("-").length == 2) num1 = num1.split("-")[1], neg[1] = true;
if (stringMode2 && num2.split("-").length == 2) num2 = num2.split("-")[1], neg[2] = true;
if (neg[1] != neg[2] && mode != 1 && mode != 2) neg[0] = true;
if (stringMode1) num1 = num1.split('').filter(w => w != ",");
if (stringMode2) num2 = num2.split('').filter(w => w != ",");
num1pos = num1.indexOf("."), decimal1 = num1pos != -1 ? num1.filter(w => w != ".").length - num1pos : 0, num2pos = num2.indexOf("."), decimal2 = num2pos != -1 ? num2.filter(w => w != ".").length - num2pos : 0, decimal = mode == 1 || mode == 2 ? Math.max(decimal1, decimal2) : mode == 3 ? decimal1 + decimal2 : decimal1 - decimal2, maxChar = Math.max(num1.length, num2.length);
for (var i = 0; !skip && num2.length == maxChar && i < num2.length && (((neg[1] || neg[2]) && mode == 1) || mode == 2); i++)
if (+num2[i] > +num1[i]) neg[0] = true, skip = true;
if (decimal < 0) decimal = 0;
if (maxChar == num2.length && mode == 3) num1 = [num2, num2 = num1][0]
if (decimal1 != decimal2 && [1, 2].indexOf(mode) > -1) {
if (decimal1 == decimal)
for (var i = 0; i < decimal1 - decimal2; i++) num2.push("0");
else if (decimal2 == decimal)
for (var i = 0; i < decimal2 - decimal1; i++) num1.push("0");
}
if (num1.length != num2.length && [1, 2].indexOf(mode) > -1) {
numl = [num1.length, num2.length];
if (maxChar == numl[0])
for (var i = 0; i < numl[0] - numl[1]; i++) num2.unshift("0");
else if (maxChar != num1[0])
for (var i = 0; i < numl[1] - numl[0]; i++) num1.unshift("0");
}
if (mode == 3 && neg.every(e => (e == true))) neg[0] = false;
return {
num1: {
num: num1,
isNeg: neg[1],
decimals: decimal1
},
num2: {
num: num2,
isNeg: neg[2],
decimals: decimal2
},
isNeg: neg[0],
maxChar: maxChar,
decimals: decimal
};
}
function formatNums(final, decimals, neg) {
if (typeof final == "string") {
if (decimals > 0) {
final = final.split("");
final.splice(final.length - decimals, 0, ".");
final = final.join("");
}
} else if (typeof final == "object") {
if (decimals > 0) {
final = final.reverse();
final.splice(final.length - decimals, 0, ".");
final = final.join("");
} else final = final.reverse().join("");
}
final = neg[0] ? "-" + final : final;
final = ["", ".", "-"].indexOf(final) > -1 ? "0" : final;
return final;
}
function add() {
function tempadd(num1, num2) {
var parsedNums = parseNums(num1, num2, 1),
neg = [parsedNums.isNeg, parsedNums.num1.isNeg, parsedNums.num2.isNeg],
maxChar = parsedNums.maxChar,
decimal = [parsedNums.decimals, parsedNums.num1.decimals, parsedNums.num2.decimals],
num1 = parsedNums.num1.num,
num2 = parsedNums.num2.num,
time, final = [],
carry = "0",
finali;
if (neg[2]) return sub(parsedNums.num1, {
num: num2,
isNeg: false,
decimals: decimal[1]
});
else if (neg[1]) return sub(parsedNums.num2, {
num: num1,
isNeg: false,
decimals: decimal[2]
});
for (var i = maxChar - 1; i >= 0; i--) {
finali = maxChar - i - 1;
if (time != i + 1) carry = "0";
final[finali] = String(+num1[i] + (+num2[i]) + (+carry));
if (+final[finali] > 9) {
var temp = final[finali].split('');
final[finali] = temp[1], carry = temp[0], time = i;
if (i - 1 < 0) final.push(carry);
}
}
return formatNums(final, decimal[0], neg);
}
var permfinal, a = arguments;
if (Array.isArray(a[0])) a = a[0];
permfinal = tempadd(a[0], a[1]);
for (var i = 2; i < a.length; i++) permfinal = tempadd(permfinal, a[i]);
return permfinal;
}
function sub() {
function tempsub(num1pre, num2pre) {
var parsedNums = parseNums(num1pre, num2pre, 2),
neg = [parsedNums.isNeg, parsedNums.num1.isNeg, parsedNums.num2.isNeg],
maxChar = parsedNums.maxChar,
decimal = [parsedNums.decimals, parsedNums.num1.decimals, parsedNums.num2.decimals],
num1 = parsedNums.num1.num,
num2 = parsedNums.num2.num,
final = [],
finali, fans;
if (neg[0] && !neg[1] && !neg[2]) num1 = [num2, num2 = num1][0];
else if (neg[1] && neg[2]) num1 = [num2, num2 = num1][0];
else if (neg[2] && !neg[1]) return add(parsedNums.num1, {
num: num2,
isNeg: false,
decimals: decimal[2]
});
else if (neg[1] && !neg[2]) return "-" + add({
num: num1,
isNeg: false,
decimals: decimal[1]
}, parsedNums.num2);
for (var i = maxChar - 1; i >= 0; i--) {
finali = maxChar - i - 1, fans = num1[i] - num2[i];
if (fans < 0 && i != 0) {
var j = i - 1;
final[finali] = String(fans + 10), num1[j] = String(num1[j] - 1);
while (num1[j] < 0 && j != 0) num1[j] = String((+num1[j]) + 10), j = j - 1, num1[j] = String(num1[j] - 1);
} else if (fans < 0 && i == 0) final[finali] = String(fans).split("-")[1];
else final[finali] = fans;
}
return formatNums(final, decimal[0], neg);
}
var permfinal, a = arguments;
if (Array.isArray(a[0])) a = a[0];
permfinal = tempsub(a[0], a[1]);
for (var i = 2; i < a.length; i++) permfinal = tempsub(permfinal, a[i]);
return permfinal;
}
function isLessThan() {
function templessthan(num1, num2) {
var num = sub(num2, num1);
if (num.split("-").length == 1 && num != 0) return true;
return false;
}
var permfinal, a = arguments;
if (Array.isArray(a[0])) a = a[0];
permfinal = templessthan(a[0], a[1]);
for (var i = 2; i < a.length; i++) permfinal = templessthan(permfinal, a[i]);
return permfinal;
}
function multi() {
function tempmulti(num1pre, num2pre) {
var parsedNums = parseNums(num1pre, num2pre, 3),
neg = [parsedNums.isNeg, parsedNums.num1.isNeg, parsedNums.num2.isNeg],
final = "",
decimals = parsedNums.decimals,
numArray = [],
num2 = parsedNums.num2,
num1 = parsedNums.num1;
if (num2.num.length == 1 && num2.num[0] == "1") return formatNums(num2.num, decimals, neg);
else if (num2.length == 1 && num2[0] == "0") return "1";
else {
final = add(num1, num1);
for (var i = "2"; isLessThan(i, num2); i = add({
num: i.split(""),
isNeg: false,
decimals: 0
}, {
num: ["1"],
isNeg: false,
decimals: 0
})) final = add(final, num1);
}
return formatNums(final, decimals, neg);
}
var permfinal, a = arguments;
if (Array.isArray(a[0])) a = a[0];
permfinal = tempmulti(a[0], a[1]);
for (var i = 2; i < a.length; i++) permfinal = tempmulti(permfinal, a[i]);
return permfinal;
}
function expo() {
function tempexpo(num1pre, num2pre) {
var parsedNums = parseNums(num1pre, num2pre, 5),
num1 = parsedNums.num1,
num2 = parsedNums.num2,
decimals = parsedNums.decimals,
decimal2 = parsedNums.num2.decimals,
neg = [parsedNums.isNeg, parsedNums.num1.isNeg, parsedNums.num2.isNeg],
numArray = [],
final = "";
if (neg[1]) num1.num.unshift("-");
if (neg[2]) num2.num.unshift("-");
if (decimal2 > 0) {
// root_of_decimal2*10(num1)**(num2*(10*decimal2))
alert("Decimal exponents aren't supported yet");
throw new TypeError("Decimal exponents aren't supported yet");
} else {
if (num2.num.length == 1 && num2.num[0] == "1") return formatNums(num2.num, decimals, false);
else if (num2.num.length == 1 && num2.num[0] == "0") return "1";
else {
final = multi(num1, num1);
for (var i = "2"; isLessThan(i, num2); i = add({
num: i.split(""),
isNeg: false,
decimals: 0
}, {
num: ["1"],
isNeg: false,
decimals: 0
})) {
final = multi(final, num1);
console.log(num1, num2, i);
}
return final;
}
//Need to fix div -> if (neg[2]) return div("1", final);
}
}
var permfinal, a = arguments;
if (Array.isArray(a[0])) a = a[0];
permfinal = tempexpo(a[0], a[1]);
for (var i = 2; i < a.length; i++) permfinal = tempexpo(permfinal, a[i]);
return permfinal;
}
console.log(expo("2", "64"));
Why is this happening? Is there a work-around?
If you saw the previous post, sorry. I've been very frustrated with this bug.
Doing the following:
var num1save = JSON.parse(JSON.stringify(num1));
var num2save = JSON.parse(JSON.stringify(num2));
sets a save variable that isn't just a reference but is instead a good copy and then doing this to set the save:
num1 = JSON.parse(JSON.stringify(num1save));
num2 = JSON.parse(JSON.stringify(num2save));
doesn't prevent the problem from happening, but prevents it from causing any issues. Appling this in a way other than in the for loop would prevent the issue from happening.
Hi This is my first time using this website, I did do some research about how to convert lowercase letter to uppercase letter but still filles. The requirement is to check if "even", covert the even digit letter to different type(lower to upper or upper to lower). below is my code:
function question4(str,pos)
{ var newLetter;
var kkk=str;
if (pos='even')
{
for (var i=0;i<str.length;i=i+2)
{
if (str[i].toString()==str[i].toString().toUpperCase())
{
newLetter=str[i].toString().toLowerCase();
kkk[i]=newLetter;
}else
{
newLetter=str[i].toUpperCase();
kkk[i]=newLetter;
}
}
}else if (pos='odd')
for ( i=0;i<str.length;i=i+2)
{
if (str[i]===str[i].toLowerCase())
{
alert('3');
}else if (str[i]===str[i].toUpperCase())
{
alert('4');
}
}
return kkk;
}
the requirement is: Write a function to change the case of all the characters in string based on their position which matches the value of the pos parameter function. function (str, pos [even|odd]). Example ( (‘abCd’, ‘odd’) return Abcd)
Update: now I have make "odd" condition working, but "even "still is not working, can any one take a look why?
function question4(strr,pos) {
var result ;
var sum="";
var aaa;
for (var i = 0; i <= strr.length - 1; i = i + 1)
{
if (pos == "odd"&&i%2==0)
{ aaa=strr.charCodeAt(i);
if (aaa >= 65 && aaa <= 90 )
{
result = String.fromCharCode(aaa + 32);
} else
result = String.fromCharCode(aaa - 32);
}
else if (pos == "even"&&i%2==1)
{
if (aaa >= 65 && aaa <= 90 )
{
result= String.fromCharCode(aaa + 32);
} else
result = String.fromCharCode(aaa - 32);
}else result=strr[i];
sum+=result;
}
return sum;
}
To achieve this, you can construct a string by concating char by char:
function question4(strInput, pos) {
let str = ""; // The string to construct
if (!pos || (pos !== "even" && pos !== "odd")) { // Validating pos
throw "invalid pos";
}
for (var i=0;i<strInput.length;i++) // Looping on strInput
{
let huPos = i + 1;
if ((pos === "even" && huPos%2 == 1) ||
(pos === "odd" && huPos%2 == 0)) {
/* If we want switch odd and we are on even position or if we want switch even and we are on odd position, then we add the original char
*/
str += strInput[i];
}
else {
// In others case, we switch lower to upper and upper to lower
let char = strInput[i];
str += char == char.toUpperCase() ? char.toLowerCase() : char.toUpperCase();
}
}
return str;
}
console.log(question4('abCdef', "odd")); // Return "AbcdEf"
Associated bin
EDIT:
After seeing edit, i can see you want to do it without using toLower/UpperCase. As stated in comment i think it is a bad idea in js, but to experiment you can achieve this:
const reverser = {
"a": "a".charCodeAt(0),
"z": "z".charCodeAt(0),
"A": "A".charCodeAt(0),
"Z": "Z".charCodeAt(0),
};
const conversionValueToLower = reverser.a - reverser.A;
const conversionValueToUpper = reverser.A - reverser.a;
function reverseChar(char) {
var code = char.charCodeAt(0);
// If you want to go from upper to lower
if (code >= reverser.A && code <= reverser.Z) {
// Simply add the difference between lower and upper
return String.fromCharCode(code + conversionValueToLower);
} // Same logic here
else if (code >= reverser.a && code <= reverser.z) {
return String.fromCharCode(code + conversionValueToUpper);
}
/**
Or use if you want full digit
if (code <= 90 && code >= 65) {
return String.fromCharCode(code + 32);
}
else if (code >= 97 && code <= 122) {
return String.fromCharCode(code - 32);
}
**/
return char; // Other case return original char
}
function question4(strInput, pos) {
let str = "";
if (!pos || (pos !== "even" && pos !== "odd")) {
throw "invalid pos";
}
for (var i=0;i<strInput.length;i++)
{
let huPos = i + 1;
if ((pos === "even" && huPos%2 == 1) ||
(pos === "odd" && huPos%2 == 0)) {
str += strInput[i];
}
else {
str += reverseChar(strInput[i]);
}
}
return str;
}
console.log(question4('abCdef', "odd")); // return "AbcdEf"
Associated bin
Another way could be to code utils functions imitating toLower/UpperCase
I corrected your code in your answer aswell, without changing original logic
function question4(strr,pos) {
var result ;
var sum="";
var aaa;
for (var i = 0; i <= strr.length - 1; i = i + 1)
{
if (pos == "odd"&&i%2==0)
{ aaa=strr.charCodeAt(i);
if (aaa >= 65 && aaa <= 90 )
{
result = String.fromCharCode(aaa + 32);
} else if(aaa >=97&&aaa <=122)
{ result = String.fromCharCode(aaa - 32);}
else {result=strr[i];}
}
else if (pos == "even"&&i%2==1)
{ aaa=strr.charCodeAt(i);
if (aaa >= 65 && aaa <= 90 )
{
result= String.fromCharCode(aaa + 32);
} else if(aaa >=97&&aaa <=122)
{ result = String.fromCharCode(aaa - 32);}
else {result=strr[i];}
}else {result=strr[i];}
sum+=result;
}
return sum;
}
console.log(question4("abCd", "odd")) // return Abcd;
A simple solution for this question
// Function used to invert the letter case
const changeCase = c => {
if (c === c.toUpperCase()) return c.toLowerCase()
return c.toUpperCase()
}
const swapCaseConditional = (str, pos) => {
// Use split method to convert string into array and map the array
return str.split('').map((c, index) => {
if (pos === 'even') {
// if pos and index are even, change the letter case
if (index % 2) return changeCase(c)
return c
}
else {
// if pos and index are odd, change the letter case
if (!(index%2)) return changeCase(c)
return c
}
// Convert to string
}).join('')
}
console.log(swapCaseConditional('abCd', 'odd'))
I worked two nights and finally got it working. although not fully cover all the situations, but almost there.
function question4(strr,pos) {
var result ;
var sum="";
var aaa;
for (var i = 0; i <= strr.length - 1; i = i + 1)
{
if (pos == "odd"&&i%2==0)
{ aaa=strr.charCodeAt(i);
if (aaa >= 65 && aaa <= 90 )
{
result = String.fromCharCode(aaa + 32);
} else
result = String.fromCharCode(aaa - 32);
}
else if (pos == "even"&&i%2==1)
{ aaa=strr.charCodeAt(i);
if (aaa >= 65 && aaa <= 90 )
{
result= String.fromCharCode(aaa + 32);
} else if(aaa >=97&&aaa <=122)
{ result = String.fromCharCode(aaa - 32);}
else {result=strr[i];}
}else {result=strr[i];}
sum+=result;
}
return sum;
}
I'm checking for integer values in node.js using IsNaN function.
Unexpectedly, this function validates the strings like 1E267146, 1E656716 , 914E6583 to be numbers, as these strings are exponential values. Any way to work around this? In actual scenario i wont get any exponential values.
ECMA6 defines Number.isInteger as follows:
Javascript
function isInteger(nVal) {
return typeof nVal === "number" && isFinite(nVal) && nVal > -9007199254740992 && nVal < 9007199254740992 && Math.floor(nVal) === nVal;
}
but this will also accept scientific notation
console.log(isInteger(1e6));
console.log(isInteger(+"1e6"));
jsfiddle
You need to be clear as to what your definitions/expectations are.
My guess is that you may want something like this, if you are testing strings and have no limits on the max or min integer.
Javascript
function isStringNumericalInteger(testValue) {
return typeof testValue === "string" && /^[\-+]?[1-9]{1}\d+$|^[\-+]?0$/.test(testValue);
}
console.log(isStringNumericalInteger("9007199254740991"));
console.log(isStringNumericalInteger("-123216848516878975616587987846516879844651654847"));
console.log(isStringNumericalInteger("1.1"));
console.log(isStringNumericalInteger("-1.1"));
console.log(isStringNumericalInteger("1e10"));
console.log(isStringNumericalInteger("010"));
console.log(isStringNumericalInteger("0x9"));
console.log(isStringNumericalInteger(""));
console.log(isStringNumericalInteger(" "));
console.log(isStringNumericalInteger());
console.log(isStringNumericalInteger(null));
console.log(isStringNumericalInteger([]));
console.log(isStringNumericalInteger({}));
Output
true
true
false
false
false
false
false
false
false
false
false
false
false
jsfiddle
If you want to bound the range to what javascript can represent numerically as an integer then you will need to add a test for && +testValue > -9007199254740992 && +testValue < 9007199254740992
If you don't like using RegExs, you can also accomplish this with a parser. Something like this:
Javascript
function isCharacterDigit(testCharacter) {
var charCode = testCharacter.charCodeAt(0);
return charCode >= 48 && testCharacter <= 57;
}
function isStringNumericalInteger(testValue) {
var start = 0,
character,
index,
length;
if (typeof testValue !== "string") {
return false;
}
character = testValue.charAt(start);
if (character === "+" || character === "-") {
start += 1;
character = testValue.charAt(start);
}
start += 1;
length = testValue.length;
if ((length > start && character === "0") || !isCharacterDigit(character)) {
return false;
}
for (index = start; index < length; index += 1) {
if (!isCharacterDigit(testValue.charAt(index))) {
return false;
}
}
return true;
}
jsfiddle
I would use something like below code to validate number input. First I parse the given value to float and then check isNaN().
var isNumber = function (obj) {
return !isNaN(parseFloat(obj)) && isFinite(obj);
};
I think this is what you need in your case (i hate regex because this is not very good for the performance but..)
http://jsbin.com/EQiBada/1/
var NMAX = Math.pow(2, 53);
function isNumeric(n) {
n = n < 0 ? n * -1 : n;
var r = /^\d+$/.test(n);
if (r === true)
{
return parseInt(n, 10) >= (NMAX * -1) + 1 && parseInt(n, 10) <= NMAX;
}
return false;
}
Minified
var NMAX = Math.pow(2, 53);
function isNumericMin(n) {
n = n < 0 ? n * -1 : n;
return /^\d+$/.test(n) === true ? parseInt(n, 10) >= (NMAX * -1) + 1 && parseInt(n, 10) <= NMAX : false;
}
var i = '1E267146'
if(isNaN(i) || !isFinite(i) !! i=="")
{
// do stuff
}
else
{
// do stuff
}
I have a found a number of solutions on here for a counter, animating from one total to another.
Here's my what I'm using now:
jQuery.fn.extend({
ts : function (from, to, time) {
var steps = 1,
self = this,
counter;
if (from - to > 0) {
steps = -1;
};
from -= steps;
function step() {
self.text(from += steps);
if ((steps < 0 && to >= from) || (steps > 0 && from >= to)) {
clearInterval(counter);
};
};
counter = setInterval(step, time || 5);
}
});
var total = $('.total').ts(56000,56941);
It works well. However, I would like to add a comma to the total, something like 56,941. Is this possible?
I guess this will do it:
jQuery.fn.extend({
ts: function(from, to, time) {
var steps = 1, self = this, counter;
if (from - to > 0) steps = -1;
from -= steps;
function step() {
var x = (from += steps).toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
self.text(x);
if ((steps < 0 && to >= from) || (steps > 0 && from >= to)) {
clearInterval(counter);
};
};
counter = setInterval(step, time || 5);
}
});
FIDDLE
From somewhere on the web...
function formatComma(x){
return (x+'').replace( /\B(?=(\d{3})+(?!\d))/g, ',');
}
I like my own solution of reversing the string better as it is easier to understand the logic...
function formatComma(x){
// prepare the input as a string ready for manipulating and returning
return (x+'')
// reverse the string (by converting to array)
.split("").reverse().join("")
// replace 3 digits in a row, with themselves and a comma
// so long as the digits are followed by a non-word boundary
.replace(/(\d{3})\B/g,'$1,')
// reverse it all again
.split("").reverse().join("")
}
This will work. The function is taken from http://ntt.cc/2008/04/25/6-very-basic-but-very-useful-javascript-number-format-functions-for-web-developers.html. Very handy
jQuery.fn.extend({
ts : function (from, to, time) {
var steps = 1,
self = this,
counter;
if (from - to > 0) {
steps = -1;
};
from -= steps;
function step() {
self.text(addCommas(from += steps));
if ((steps < 0 && to >= from) || (steps > 0 && from >= to)) {
clearInterval(counter);
};
};
counter = setInterval(step, time || 5);
}
});
var total = $('.total').ts(56000,56941);
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;
}
Sure it is! You can check this plugin (http://code.google.com/p/jquery-numberformatter/) and implement it in yours :-)