Perform a replace on a integer? - javascript

I promise that I've done my homework on this. It's a basic question, but I'm not terribly familiar with Jquery. Assume the following...
var cac = parseInt($("#currentAccess").val());
var acn = parseInt($("#addCapital").val());
var tn = (cac + acn);
How do I then take the variable tn, do a replace on it, and output it? This is an example that doesn't work...
$("#totalNeedG").append("<p>$" + tn.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") + "</p>");
Thanks for this simple help!

.replace() is a String method. Not a Number method.
Convert it to a String.
var tn = ((cac + acn) + '');

String(yourNumber) returns a string containing your number.
To convert it back, use parseInt(yourString, 10).
And, as you are not doing it, ALWAYS use the second argument if parseInt(str, base)! If you don't, the base is determined automatically which is almost never what you want:
parseInt('010') == 8 // 0-prefix means octal
parseInt('0xff') == 255 // 0x-prefix means hex
While it's unlikely that somebody puts a number starting with 0x in a field chances are high someone puts a leading zero for some reason.

Related

Cut from the third decimal without rounding

I know it's quite low quality of question but I get little bit confused now.
Here is the thing What I want to do.
100000 => 100.000
9997080000 => 9997080.000
I want to cut from the third decimal without rounding.
How can I do this? I used the toFixed() but all I want to do is just cut from third decimal. I think I'm complicated now.
It will be simple. Plz let me know. Thanks
From what I understand, this is what you want:
var number = "9002764000";
var result = number.slice(0, -3) +"."+ number.slice(-3);
console.log(result);
This will add a . after the last three digits i.e 9002764000 -> 9002764.000
https://jsfiddle.net/5yqhr7mo/
Hope it helps!
It sounds like you want a value for display. If so, you want to turn the number into a string (since numbers don't intrinsically have any particular number of digits to the right of the decimal). You can then easily insert the . before the last three digits using substring and substr:
function formatForDisplay(num) {
var str = String(num);
return str.substring(0, str.length - 3) + "." + str.substr(-3);
}
function test(num) {
console.log(num, "=>", formatForDisplay(num));
}
test(100000);
test(9997080000);
Alternatively, you could use String#replace and add a dot.
var number = 9002764000;
console.log(Math.floor(number).toString().replace(/(?=...$)/, '.'));
what about :
function formatNumber(num){
num=num/1000;
return num.toFixed(3);
}
console.log(formatNumber(9997080000));
console.log(formatNumber(100000000));
which will return what you expect if you work with integer
Math.floor() will round down essentially cutting off everything to the right of decimal point.

Javascript adding numbers as if they were a string [duplicate]

This question already has answers here:
Javascript (+) sign concatenates instead of giving sum of variables
(14 answers)
Closed 6 years ago.
I have been playing around with cookies for the first time, and I have saving part of it completed. The data I'm saving are numbers and the most important part of these nubers is that I can add, subtract and so on with these. However when I try to add a number to one of my saved parametres it adds them as if they were text.
Example:
I have a cookie called value, and when I want this value I use a script I found by Jeffery To that looks like this:
function readCookie(name) {
return (name = new RegExp('(?:^|;\\s*)' + ('' + name).replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') + '=([^;]*)').exec(document.cookie)) && name[1];
}
After I have collected this cookie I want to add one to it. Lets say that value equals nine, when it should look like this: value + 1 = 10. Simple math. However it gives me this 91. Why does it do this? I know that it is because it thinks the numbers are a string of text, but how can I get this to behave like numbers?
Solution
After reading the comments I learned that i needed to put my value inside a parseInt(). So i simply modified the funtion to say:
function readCookie(name) {
return parseInt((name = new RegExp('(?:^|;\\s*)' + ('' + name).replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') + '=([^;]*)').exec(document.cookie)) && name[1]);
}
The + operator in JavaScript can mean mathematical addition or string concatenation. The one you get is based on the implicit type of the operands. If one of the operands is a string, the other will be converted to a string and you'll get concatenation.
The trick is to do the math on the numbers first (you can surround the math portion with parenthesis or do the math in a separate statement) and then inject the result into your string.
To force a string containing a number character into a number, you can use parseInt() and parseFloat():
var result = parseInt(value, 10) + 1;
Note that with parseInt(), you should supply the optional second argument, which specifies the radix for the operation. If the first argument happens to refer to a string that contains a hex value, the result will be based on hex, not base 10. That's why 10 is used in my example.
Also note that both parseInt() and parseFloat() stop after finding the first non-valid characters that can't be treated as numbers. So, in a string like this: "Scott7Marcy9", you would get NaN.
Cookies are saved as string values as you guessed. To get your desired effect, you're going to need to parse your value. If you are absolutely sure it will be an integer, use:
parseInt(value) + 1

Javascript String to int conversion

I have the following JS immbedded in a page:
var round = Math.round;
var id = $(this).attr("id");
var len = id.length;
var indexPos = len -1; // index of the number so that we can split this up and used it as a title
var pasType = id.substring(0, indexPos); // adult, child or infant
var ind = round(id.substring(indexPos)); // converts the string index to an integer
var number = (id.substring(indexPos) + 1); // creates the number that will go in the title
window.alert(number);
id will be something like adult0, and I need to take that string and split it into adult and 0 - this part works fine.
The problem comes in when I try to increment the 0. As you can see I use Math.round to convert it to an integer, and then add 1 to it - I expect 0 to be 1 after this. However, it doesn't seem to be converting it to integer, because I get 01, not 1. When testing this with adult1 the alert I get is 11.
I'm using this question for reference, and have also tried var number += id.substring(indexPos);, which breaks the JS (unexpected identifier '+=')
Does anyone know what I'm doing wrong? Is there a better way of doing this?
The parseInt() function parses a string and returns an integer,10 is the Radix or Base
[DOC]
var number = parseInt(id.substring(indexPos) , 10 ) + 1;
This is to do with JavaScript's + in operator - if a number and a string are "added" up, the number is converted into a string:
0 + 1; //1
'0' + 1; // '01'
To solve this, use the + unary operator, or use parseInt():
+'0' + 1; // 1
parseInt('0', 10) + 1; // 1
The unary + operator converts it into a number (however if it's a decimal it will retain the decimal places), and parseInt() is self-explanatory (converts into number, ignoring decimal places).
The second argument is necessary for parseInt() to use the correct base when leading 0s are placed:
parseInt('010'); // 8 in older browsers, 10 in newer browsers
parseInt('010', 10); // always 10 no matter what
There's also parseFloat() if you need to convert decimals in strings to their numeric value - + can do that too but it behaves slightly differently: that's another story though.
Convert by Number Class:-
Eg:
var n = Number("103");
console.log(n+1)
Output: 104
Note:- Number is class. When we pass string, then constructor of Number class will convert it.
JS will think that the 0 is a string, which it actually is, to convert it to a int, use the: parseInt() function, like:
var numberAsInt = parseInt(number, 10);
// Second arg is radix, 10 is decimal.
If the number is not possible to convert to a int, it will return NaN, so I would recommend a check for that too in code used in production or at least if you are not 100% sure of the input.
Although parseInt is the official function to do this, you can achieve the same with this code:
number*1
The advantage is that you save some characters, which might save bandwidth if your code has to lots of such conversations.
Use parseInt():
var number = (parseInt(id.substring(indexPos)) + 1);` // creates the number that will go in the title
If you are sure id.substring(indexPos) is a number, you can do it like so:
var number = Number(id.substring(indexPos)) + 1;
Otherwise I suggest checking if the Number function evaluates correctly.

Adding +1 to jQuery value of a readonly text input field

I am using a function where I have a readonly text input, and when I execute the function I want the number value + 1. So let's say I have 60, when I execute the function, the number returned should be 61.
But instead it's coming out 601, which is just adding the number 1 to the string. Any clue as to what is going on? Subtraction, multiplication and division all work fine. Here is a snippet
var num= $("#originalnum").val() + 1;
$("#originalnum").val(num);
And yes i've tried a few different variations, am I missing something?
A simple unary + is sufficient to turn a string into a number in this case:
var num = +$("#originalnum").val() + 1;
$("#originalnum").val(num);
The problem is that .val() returns the value of the element as a string, and when you use the + operator on a string it does string concatenation. You need to convert the value to a number first:
var num = +$("#originalnum").val() + 1; // unary plus operator
// OR
var num = Number($("#originalnum").val()) + 1; // Number()
// OR
var num= parseFloat($("#originalnum").val()) + 1; // parseFloat()
// OR
var num= parseInt($("#originalnum").val(),10) + 1; // parseInt()
Note that if you use parseInt() you must include the radix (10) as the second parameter or it will (depending on the browser) treat strings with a leading zero as octal and strings with a leading "0x" as hexadecimal. Note also that parseInt() ignores any non-numeric characters at the end of the string, including a full-stop that the user might have intended as a decimal point, so parseInt("123.45aasdf",10) returns 123. Similarly parseFloat() ignores non-numeric characters at the end of the string.
Also if it's a user-entered value you should double-check that it actually is a number and perhaps provide an error message if it isn't.
When you use the *, / or - operators JS tries to convert the string to a number automatically, so that's why those operators "work" (assuming the string can be converted).
You should use the parseInt function and make sure the value is number(use isNaN function):
var val = $("#originalnum").val();
var num = 0;
if ( !isNaN(val) )
num= parseInt(val) + 1;
Use parseInt():
var num= parseInt($("#originalnum").val(),10) + 1;
So your number is treated as an integer instead of a string (as .val() treats the result as string by default)
If you don't like the above code spelling, you can try it this way too.
$("#originalnum").val(function() {
$(this).val(parseInt($(this).val()) + 1)
});

parseInt alternative

Firstly - my description ;)
I've got a XmlHttpRequests JSON response from the server.
MySQL driver outputs all data as string and PHP returns it as it is, so any integer is returned as string, therefore:
Is there any fast alternative (hack) for parseInt() function in JS which can parse pure numeric string, e.g.
var foo = {"bar": "123"};
...
foo.bar = parseInt(foo.bar); // (int) 123
To convert to an integer simply use the unary + operator, it should be the fastest way:
var int = +string;
Conversions to other types can be done in a similar manner:
var string = otherType + "";
var bool = !!anything;
More info.
Type casting in JavaScript is done via the constructor functions of the built-in types without new, ie
foo.bar = Number(foo.bar);
This differs from parseInt() in several ways:
leading zeros won't trigger octal mode
floating point values will be parsed as well
the whole string is parsed, i.e. if it contains additional non-numeric characters, the return value will be NaN
First off, have you actually documented that it's slow and is causing problems? Otherwise, I wouldn't bother looking for a solution, because there really isn't a problem.
Secondly, I would guess that since parseInt is a native JS-method, it would be implemented in a way that is very fast, and probably in the native language of the VM (probably C, depending on the browser/VM). I think you could have some trouble making a faster method out of pure JS. =)
Of course, I'm not a JS guru, so I don't know for sure, but this is what my intuition tells me, and tends to be the standard answer to "how would I make a faster alternative for libraryFunction()?" questions.
Cast it to an int in PHP before you json_encode() it:
$foo->bar = (int)$foo->bar;
print('var foo = ' . json_encode($foo));
Incidentally, when using parseInt it's good practice to always specify the second parameter unless you really want string starting with 0 to be interpreted as octal and so on:
parseInt('010', 10); // 10
Fast shortcut to parseInt is
("78.5" | 0) //bitwise or forces the string to parse as int
This is what ASM uses to represent ints in js.
You aren't going to get better than parseInt, but the real bug is that the PHP is providing what is supposed to be a number as a string.
And ditto to what Daniel said - don't go looking for micro-optimisations like this until you have benchmarked your code and discovered that it's worth doing.
The Number constructor also exists, but it should be the same as parseInt in term of speed (as already said you should correct the PHP part instead of the javascript one anyway) :
var i = "123";
i = new Number(i); // Number numeric wrapper
var j = "123";
j = Number(j); // Number primitive
BTW if someone is interested i searched by curiosity for the V8 (Google chrome) implementation of parseInt and it's here on google code.
How slow can it be? How many times per second is this process being called? How many different numeric return values are there? I whipped together a script and tested 100,000 numbers. Parsing them from strings took 687ms. Searching them in an array took 541ms. That's a very small improvement. I agree with other posters. You may not get better than the native parseInt() method.
Casting is a wee bit faster than parsing but slower than searching.
Also, in Firefox the fastest method turns out to be parseInt() followed by searching. Firefox also turned out to be 6 times faster on average than IE. Interesting.
Cool idea using the unary operator. In Firefox that turned out to be comparable to parseInt(). In IE it turned out to be the fastest method.
if the objects are larger you could try JSON, it is a typed format so you do not need to convert the values.
This solution is faster than parseInt() if you parse strings of decimal integer that is 20 or less in length. For some browser, you may still be faster than parseInt() up to 33 digits in length. Also, you still be faster than auto-cast.
It is because, the parseInt() for the browser does take some time to warm up, so if you only using a simple method to parse, you beat it for a while until it catches up. Don't use this for nodeJS though. When run parseInt() from nodeJS, it is startup time is a lot less than when running from a browser.
45 is the '-' sign in ASCII, 43 is the '+' sign in ASCII. 48 is '0'. Only 48 to 57 xor 48 become 0 - 9(in their order). No other numbers xor 48 yields 0-9.
This will return undefined if the string is not a valid decimal integer string or if the string is empty. It throws a string with value "Not a string" if the input is not of type string.
var toNumber = function (input) {
if ( typeof input !== "string" ) throw "Not a string";
var length = input.length;
if ( length === 0 ) return;
var c1 = input.charCodeAt(0);
if ( c1 === 45 || c1 === 43 ){
if ( length === 1 ) return;
var start = 1;
} else {
var start = 0;
}
var out = 0, c;
while( start < length && input.charCodeAt(start) === 48 ) start++;
for ( ; start < length; start++){
c = input.charCodeAt(start) ^ 48;
if ( c > 9 ) return;
out = (out * 10) + c;
}
if ( c1 === 45 ) return out * -1;
return out;
}

Categories