Javascript String to int conversion - javascript

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.

Related

Convert negative number in string to negative decimal in JavaScript

I have a string : "-10.456"
I want to convert it to -10.465 in decimal (using JavaScript) so that I can compare for greater than or lesser than with another decimal number.
Regards.
The parseInt function can be used to parse strings to integers and uses this format: parseInt(string, radix);
Ex: parseInt("-10.465", 10); returns -10
To parse floating point numbers, you use parseFloat, formatted like parseFloat(string)
Ex: parseFloat("-10.465"); returns -10.465
Simply pass it to the Number function:
var num = Number(str);
Here are two simple ways to do this if the variable str = "-10.123":
#1
str = str*1;
#2
str = Number(str);
Both ways now contain a JavaScript number primitive now. Hope this helps!
In javascript, you can compare mixed types. So, this works:
var x = "-10.456";
var y = 5.5;
alert(x < y) // true
alert(x > y) // false
the shortcut is this:
"-3.30" <--- the number in string form
+"-3.30" <----Add plus sign
-3.3 <----- Number in number type.

From character to binary (adding the left 0)

You can convert from char to binary in JS using this code:
var txt = "H";
bits = txt.charCodeAt(0).toString(2); //bits=1001000
The result is mathematically correct but no literally, i mean, there is a missing 0 to the left, that again, is correct, but I wonder if there is a way to make it consider the left zeros.
You need a byte? Try this:
var txt = "H",
bits = txt.charCodeAt(0).toString(2),
aByte = new Array(9 - bits.length).join('0') + bits;
The snippet creates a new array with length of missing bits + 1, then it converts the newly created array to a string with amount of zeroes needed. 9 is the wanted "byte length" + 1.
However, this is relatively slow method, if you're having a time-critical task, I'd suggest you to use while or for loop instead.
charCodeAt() returns the code of a character, which is a general number.
A number itself does not have any kind of preffered alignment.
By convention numbers are printed without any leading zeros.
In fact, charCodeAt() returns unicode character code,
which in general can take more than 8 bits to store.
Therefore such behaviour is correct.
Try this
var bits = txt.charCodeAt( 0 ).toString( 2 );
var padding = 8 - bits.length;
res = [ ];
res.push( new Array( padding+1 ).join( '0' ) + bits );

numbers and toFixed , toPrecision in Javascript?

Regarding the famous issue of 1.01+1.02 which is 2.0300000000000002
one of the workarounds is to use toFixed : e.g.
(1.01+1.02).toFixed(2) --->"2.03"
But I saw a solution with toPrecision
parseFloat((1.01+1.02).toPrecision(10))-->"2.03"
But lets have a look at n in
toFixed(n)
toPrecision(n)
How would I know what is n ?
0.xxxxxxxxxxx
+
0.yyyyyyyyyyyyy
---------------------
0.zzzzzzzzzzzzzzzzzzzzzzzzz
^
|
-----??????------
each number being added can have a different decimal digits...
for example :
1.0002+1.01+1.03333--> 3.0435300000000005
how would I calculate the n here ? what is the best practice for this (specific) issue ?
For addition as in this situation I would check the number of decimal places in each operand.
In the simplest of situations the number of decimal places in the operand with the greatest number of decimal places is the value of n.
Once you have this, use which ever method you like to truncate your value. Then get rid of trailing zeros.
You may encounter trailing zeros in situations such as 1.06 + 1.04, the first step would take you to 1.10 then truncating the zero would give 1.1
In your last example 1.0002+1.01+1.03333 greatest number of decimal places is 5 so you are left with 3.04353 and there are no trailing zeros to truncate.
This returns the expected output:
function add(){
// Initialize output and "length" properties
var length = 0;
var output = 0;
// Loop through all arguments supplied to this function (So: 1,4,6 in case of add(1,4,6);)
for(var i = 0; i < arguments.length; i++){
// If the current argument's length as string is longer than the previous one (or greater than 0 in case of the first argument))
if(arguments[0].toString().length > length){
// Set the current length to the argument's length (+1 is to account for the decimal point taking 1 character.)
length = arguments[0].toString().length +1;
}
// Add the current character to the output with a precision specified by the longest argument.
output = parseFloat((output+arguments[i]).toPrecision(length));
}
// Do whatever you with with the result, here. Usually, you'd 'return output;'
console.log(output);
}
add(); // Returns 0
add(1,2,3); // Returns 6
add(1.01,2.01,3.03); // Returns 6.05
add(1.01,2.0213,3.3333); // Returns 6.3646
add(11.01,2.0213,31.3333); // Returns 44.3646
parseFloat even gets rid of trailing zero's for you.
This function accepts as many numbers as parameters as you wish, then adds these together taking the numbers' string length into account, when adding them. The precision used in the addition is dynamically modified to fit the "currently added" argument's length.
Fiddle
If you're doing calculations, you have a couple of choices:
multiply the numbers by eg 100, to convert to integers, then do the calculations, then convert back again
do the calculations, dont worry about the rounding errors, then round the result at display time
If you're dealing with money/currencies, the first option is probably not a bad option. If you're just doing scientific maths, I would personally not worry about it, and just round the results at display time, eg to 6 significant figures which is the default for my c++ compiler (gcc; not sure if it is in the c++ standards or not, but if you print 1.234567890 in gcc c++, the output is 1.23457, and the problem is avoided)
var a = 216.57421;
a.toPrecision(1); // => '200' because 216 with 1 < 5;
a.toPrecision(2); // => '220' because 216 with 6 >= 5;
a.toFixed(1); // => 216.6 because 7 >= 5;
a.toFixed(2); // => 216.57 because 4 < 5;

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)
});

whole number in javascript?

I get 28.6813276578 when i multiply 2 numbers a and b, how can i make it whole number with less digits
and also, when i multiply again i get results after first reult like 28.681321405.4428.68 how to get only one result ?
<script>
$(document).ready(function(){
$("#total").hide();
$("#form1").submit(function(){
var a = parseFloat($("#user_price").val());
var b = parseFloat($("#selling").val());
var total = a*b;
$("#total").append(total)
.show('slow')
.css({"background":"yellow","font-size":50})
;
return false;
});
});
</script>
You can do several things:
total = total.toFixed([number of decimals]);
total = Math.round(total);
total = parseInt(total);
toFixed() will round your number to the number of decimals indicated.
Math.round() will round numbers to the nearest integer.
parseInt() will take a string and attempt to parse an integer from it without rounding. parseInt() is a little trickier though, in that it will parse the first characters in a string that are numbers until they are not, meaning parseInt('123g32ksj') will return 123, whereas parseInt('sdjgg123') will return NaN.
For the sake of completeness, parseInt() accepts a second parameter which can be used to express the base you're trying to extract with, meaning that, for instance,
parseInt('A', 16) === 10 if you were trying to parse a hexidecimal.
See Math.round(...).
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Math/round
In addition to the other answers about rounding, you are appending the answer to "total" by using
$("#total").append(total)
You need to replace the previous text rather than appending by using
$("#total").html(total)

Categories