Converting number to string to number to delete dot - javascript

I need to remove the dot in 1.400 in order to get the integer 1400, but it return 140. How do I obtain 1400 as an integer?
var var2= String(1.400) ;
var2 = var2.replace(".","");
var2=parseInt(var2);

There's no way the code you've given returns 140, since 1.400 is a number literal and gets shortened to 1.4 straight away and only then turned to string of "1.4". Therefore replacing a dot and converting to int results in 14.
It's not possible to tell JavaScript that number of 1.400 is not 1.4. You'd have to start with a string of "1.400" to get what you want.
Instead of going number -> string -> number maybe you could multiply the number by a thousand, or whatever order of magnitude is required.

Here is the problem ,
var var2= String(1.400) ;
alert(var2); //Returns 1.4 cause it is performing Number to String conversion
So , Change it to var var2= "1.400"; or var var2=number.toString();
And Update the replace to
var2.replace(/\./g,""); // : /g means all occurrence
You need to escape the . because it has the meaning of an arbitrary character in a regex.

Using this you will get your expected output.
var var2= "1.400" ;
var2 = var2.replace(".","");
var2=parseInt(var2);
Explanation:
var s1 = '2 + 2'; // creates a string primitive
var s2 = new String('2 + 2'); // creates a String object
console.log(eval(s1)); // returns the number 4
console.log(eval(s2)); // returns the string "2 + 2"

Add single-quotes around the initial string:
var var2= String('1.400');

Related

Instead of concatenation I want to add plus 1 why its not working?

var name = $(".column_nr_matching:last").attr("name");
// this gives me col_nr359
and here I add plus 1
var added_one = name + (+1);
When I look with console it gives me this:
col_nr3591
I need it to be
col_nr360
Because col_nr359 is a string, and by using +, you are concatenating 1 to that string. You need to do something like this:
document.getElementById('increment').onclick = function (){
//get the innertext from the span
var text = document.getElementById('colid').innerText;
//replace the 'col_nr' text with empty string to get the number
var nr = text.replace('col_nr','');
//parses the number to int and sums 1, then concatenate back
var new_id = 'col_nr' + (parseInt(nr) + 1);
//set the new text to the span
document.getElementById('colid').innerText = new_id;
}
<span id="colid">col_nr359</span>
<br>
<button id="increment" > Increment </button>
As mentioned, name is a string, not a number. You need to just get the number part so you can add one to it. One possible way of doing so is with a regex string replace, where you use capture group to get the number part, and replace it with that number plus one. Example:
const name = "col_nr359";
const added_one = name.replace(/(\d*)$/, m => String(+m + 1))
console.log(added_one)
col_nr359 is a String, even JavaScript can't interpret it as number, since there are characters in front.
What you have to do is split the string so you have col_nr and 359, then add 1 to the 359, then concatenate it again.
You are mixing datatypes. col_nrxxx is a string and will always be one. You have to cut out the 359, then parse it to int, then add the +1, then concat it back to the string.

Javascript/jQuery gives weird result from addition

I'm just starting javascript and jquery and now I'm stuck with this kind of problem:
var myCharacter = ('#myCharacter').css('top'); // gives 140px
var numberOnly = myCharacter.replace('px',''); // gives 140
var total = numberOnly + 20; // gives 14020 not 160
I just don't understand why this happens.
you need parseInt()
var total = parseInt(numberOnly) + 20;
because numberOnly is a string, not a number, so its adding a number to a string which results in that 14020 as a string
When you replace 'px' in '140px', you end up with a variable of string type. (javascript has types, but they are dynamic)
When you call '140'+20, the type is not converted automatically, because + is an operation that makes sense on strings: concatenation.
You should explicitly convert to a number, for example by using parseInt('140'), then the addition should work as expected.
As one of the operands in numberOnly + 20 is a string, the + operator does string concatenation, not addition.
Use the parseInt method to parse the string to a number, then you don't have to remove the px part either, as the parsing ends when it encounters non-numerical characters.
var myCharacter = parseInt(('#myCharacter').css('top'), 10);
var total = myCharacter + 20;
That's because numberOnly is a String you can cast to int by doing:
var total = +numberOnly + 20
var myCharacter = ('#myCharacter').css('top'); // gives 140px
var numberOnly = myCharacter.replace('px',''); // gives 140
var total = parseInt(numberOnly) + 20;
you are trying to add up with string so first convert it into integer,use parseInt() to do this:
var total = parseInt(numberOnly) + 20;//160
numberOnly is still of type string, i.e. it's a number of characters. Thus you currently conctenate string '140' with 20, which is implicitly converted to a string.
To fix this, convert numberOnly to an integer using [parseInt][1].

I have a string which contains a decimal point e.g. "10.00" and I want to hide it using jQuery?

I have a string which contains a decimal point e.g. "10.00" and I want to hide it using jQuery? I need to trim it to "10" from "10.00".
Many options, I'd probably go with
var foo = "10.00";
foo.split('.')[ 0 ];
Math.floor(parseInt("10.00",10));
// 10
If you need it back as a string rather than an int,
Math.floor(parseInt("10.00",10)).toString();
// "10"
Edit:
Actually, Math.floor() isn't necessary. parseInt() will do it alone:
parseInt("10.00",10).toString();
// "10"
The following will remove the decimal values by converting it to an integer:
// Returns an int of 10.
var myInteger = parseInt("10.00");
or
// Returns a string of "10".
var myString = parseInt("10.00").toString();
Or the regex way. Since we start with a String and want a String out, why bother converting back and forth to numbers ? And this will be faster than 'split'.
/[^\.]*/.exec("10.00")[0]
Pure string way to do this is
var Trim = function( n ) {
var index = n.indexOf('.');
return n.substring(0, index - 1);
};
//usage
Trim( "10.00" );
The following may be useful:
intvalue = parseInt($('#quantity').val(), 10);

Javascript string to int array

var result ="1fg";
for(i =0; i < result.length; i++){
var chr = result.charAt(i);
var hexval = chr.charCodeAt(chr)
document.write(hexval + " ");
}
This gives NaN 102 103.
Probably because it's treating the "1" as a integer or something like that. Is there a way I can convert the
"1"->string to the correct integer? In this case: 49.
So it will be
49 102 103 instead of NaN 102 103
Cheers,
Timo
The charCodeAt function takes an index, not a string.
When you pass it a string, it will try to convert the string to a number, and use 0 if it couldn't.
Your first iteration calls '1'.charCodeAt('1'). It will parse '1' as a number and try to get the second character code in the string. Since the string only has one character, that's NaN.
Your second iteration calls 'f'.charCodeAt('f'). Since 'f' cannot be parsed as a number, it will be interpreted as 0, which will give you the first character code.
You should write var hexval = result.charCodeAt(i) to get the character code at the given position in the original string.
You can also write var hexval = chr.charCodeAt(0) to get the character code of the single character in the chr string.

Javascript / Jquery - Get number from string

the string looks like this
"blabla blabla-5 amount-10 blabla direction-left"
How can I get the number just after "amount-", and the text just after "direction-" ?
This will get all the numbers separated by coma:
var str = "10 is smaller than 11 but greater then 9";
var pattern = /[0-9]+/g;
var matches = str.match(pattern);
After execution, the string matches will have values "10,11,9"
If You are just looking for thew first occurrence, the pattern will be /[0-9]+/ - which will return 10
(There is no need for JQuery)
This uses regular expressions and the exec method:
var s = "blabla blabla-5 amount-10 blabla direction-left";
var amount = parseInt(/amount-(\d+)/.exec(s)[1], 10);
var direction = /direction-([^\s]+)/.exec(s)[1];
The code will cause an error if the amount or direction is missing; if this is possible, check if the result of exec is non-null before indexing into the array that should be returned.
You can use regexp as explained by w3schools. Hint:
str = "blabla blabla-5 amount-10 blabla direction-left"
alert(str.match(/amount-([0-9]+)/));
Otherwize you can simply want all numbers so use the pattern [0-9]+ only.
str.match would return an array.

Categories