How can I remove all decimals from a number? I want to get the number as specified below. I need to remove decimal points only. I am not getting the logic for it.
If number x= 1.1.6;
then I want result as 116
and when x=0.0.6;
then I want result as 6.
Since 1.1.6 is not a valid numerical value in JavaScript, I assume that you're starting with a string. You can get the result as an integer value with:
parseInt(number.replace(/\./g, ''))
If desired, you can then turn that back into a string with no leading zeroes with:
'' + parseInt(number.replace(/\./g, ''))
try this. replace all the . using replace method and convert to integer
document.write(parseInt("1.1.6".replace(/\./g, '')))
document.write('<br>')
document.write(parseInt("0.0.6".replace(/\./g, '')))
Related
Why does parseInt("-1000-500-75-33") return -1000?
Shouldn't it return the sum of those numbers: -1608
How can I get the string "-1000-500-75-33" to return as the sum of those numbers?
parseInt will try to get a number starting from the beginning of the string.
Since - is a valid character to begin a number with, it parses the string until it finds something invalid. The second - is invalid because no integer can contain an - inside it, only digits. So it stops there and considers the number to be "finished".
Now, if you want to process the expression, you can use eval like so:
eval("-1000-500-75-33")
This will return -1608 as expected.
parseInt will not perform any computations, rather it will try to convert a string into an integer. It returns -1000 because the dash afterwards would not be considered a valid number. If you want to sum all these numbers you could split on the dash, map to Number, then reduce:
var numString = "-1000-500-75-33";
numString.split('-').map(e => Number(e)).reduce((a, b) => a - b);
Try to eval! it's safe here
eval("-1000-500-75-33").toString()
console.log(eval("-1000-500-75-33").toString());
And about type casting: After parsing -1000, which is obviously "negative 1000", It will escape casting as soon as it detect a symbol common between numbers & strings. So parseInt is seeing "-1000-500-75-33" as "-1000NotConvertableString", So left the remaining away, returning -1000 as the result of type-casting.
Since they are in a string, ParseInt does not parse the whole string, just finds the first applicable number from the start & returns it. If the start of the string cannot be parsed, it returns NaN
parseInt("-1000NOT_NUMBER") = -1000
parseInt("test-1000`) = NaN
You have to use eval function to do what you want, that evaluates given string as if it were a command entered into the console;
eval("-1000-500-75-33") = -1608
My app has a textbox on a webpage whose value is looked up and then added or subtracted to another value.
It seems to subtract well, but when adding, it interprets the value in the textbox as text, and adds on the other float as a text as well:
Here's the source code of the thing changing:
$('#mymoney').val($('#mymoney').val() + $prevevent.close);
//...or when subtracting:...//
$('#mymoney').val($('#mymoney').val() - $prevevent.close);
How to I tell the mymoney to be interpreted as a float instead of a string?
This is because .val() is reading the value as a string and concatinating. You can parse it into a integer with parseInt():
$('#mymoney').val( parseInt($('#mymoney').val()) + $prevevent.close);
For float values use parseFloat():
$('#mymoney').val( parseFloat($('#mymoney').val()) + $prevevent.close);
This is simple by using parseFloat
$('#mymoney').val(parseFloat($('#mymoney').val()) + $prevevent.close);
Because JS will interpretes the other hand to string if either operator hand is a string.
Or, you can use Number() to parse string to (int or float) number like:
$('#mymoney').val(Number($('#mymoney').val()) + $prevevent.close);
But the parseInt or parseFloat is prefer, because it acts more normally than Number. For Example, Number will parse null and "" to 0, and erase the 0 at the beginning of a number although it may represent an octal digit. Additionally, parseInt will return the correct part until it can't be parsed, like: parseInt("15abc") returns 15.
Other answers are correct. However, here is another syntactical spice of magic that will do wonders for integer values.
Instead of using parseInt you can just prepend your expression with a + and it will parse the following value to integer.
$('#mymoney').val( (+$('#mymoney').val()) + $prevevent.close);
I am making a basic game, and I have a tile system that I'm using. Each tile has an ID of "tileX", where X is a number (ex. tile1). I have a function as follows:
window.onclick = function() {
var x = event.clientX, y = event.clientY,
elementMouseIsOver = document.elementFromPoint(x, y).id;
document.getElementById("tileTell").value = elementMouseIsOver;
console.log(elementMouseIsOver);
console.log(typeof(elementMouseIsOver));
elementMouseIsOver = parseInt(elementMouseIsOver);
console.log(elementMouseIsOver);
console.log(typeof(elementMouseIsOver));
}
Line 4 of code there fills in an input field so I can visually see which tile I've clicked (I'm using this to make sure things are working properly and so I can find the tiles I need). That works fine. On line 5 when I do a console.log, it gives me the proper ID, and verifies that it is a string.
After that I want to reset the elementMouseIsOver variable to be an integer, so if the ID was tile1 I would expect the new result to be 1. But when I look at it in the console, I get NaN. And then when I check the type of it immediately after that, I get number.
The parseInt does not seem to be working properly, what am I doing wrong? I need to use the ID names of each tile for mathematical operations so this is vital to my game. I know it's probably a really dumb mistake but I am completely at a loss...
If you want parseInt() to work on strings in the way you're using it, it has to start with a digit; in your case, it starts with alphabetical characters, and so (with an implicit radix of 10) it will rightfully return NaN.
You could get the number out by using a generic method:
var num = +(elementMouseIsOver.match(/\d+/) || [])[0];
It matches the first group of digits it can find and then uses the unary plus operator to cast it into an actual number value. If the string doesn't contain any digits, it will yield NaN.
In your particular case, you could also apply parseInt() on the part that immediately follows "tile":
var num = +elementMouseIsOver.substr(4);
NaN is correct.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point.
Nothing parsed successfully.
EDIT
You could accomplish what you want by removing the non-numeric characters from the string, assuming you'll always have a string+integer as the ID. Try this:
parseInt(elementMouseIsOver.replace(/[^\d]/,""))
You need to remove the "tile" string first, so it can properly parse the value:
elementMouseIsOver = parseInt(elementMouseIsOver.substring("tile".length));
.substring("tile".length) returns a substring starting with the character after "tile" (position 4 in the string, count starts at 0), resulting in only the number of the ID (as a string).
fiddle: http://jsfiddle.net/rk96uygd/
The typeof of a NaN is number.
Use isNaN() to test if a value is NaN or Not a Number
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/isNaN
You could also use the Number() cast instead of parseInt().
you trying to parseInt on a element ID that is non-numeric, when parse fail it will return NaN (*or not a number*)
elementMouseIsOver = parseInt(elementMouseIsOver);
moreover, your elementMouseIsOver is an ID of control, I don't think .value can get the value of control
elementMouseIsOver = document.elementFromPoint(x, y).id;
I want to retrive a number value from a div and then round that number to 2 decimal places using jQuery.
So far I have the element name and value:
<div class="value">Price = £133.3223443</div>
I am using the toFixed() method to convert a number into a string then round to 2 decimal places:
var inNum = 12345.6789;
inNum.toFixed(2);
However, I am having trouble trying to read a number within the element on the page (ignoring 'Price'), rather than just rounding a number entered within the jQuery.
Parse it with regexp? :)
http://jsfiddle.net/LERFB/2/ <--- working fiddle
var price = $('div.value').text();
var parsedPrice = parseFloat(price.replace(/([^0-9\.])/g, ''));
alert(parsedPrice.toFixed(2));
You can use text() to get the value from the element, and the split() by £ to get the numerical price. Try this:
var inNum = parseFloat($('.value').text().split('£')[1]).toFixed(2);
Example fiddle
Obviously you will also need some form of verification to ensure that there is a £ character in the string to split by, and that the value retrieved is numerical.
The following regular expression will extract the floating numbers from the string and do a toFixed operation.
var inNum = parseFloat($(".value").text().match(/[\d\.\d]+/i)).toFixed(2);
Please make sure you have the value inside the container all the time.
Is there any built in method to get which can parse int from string ("23px")?
I know I can use substring and then parseInt but I want to know if there is any other way available to do this.
parseInt will grab the first set of contiguous numbers:
parseInt('23px');
returns 23.
If there is any chance there will be leading zeros, use a radix:
parseInt('23px', 10);
which is a good habit in general.
parseInt can do it. Just use:
var num = parseInt("23px", 10);
It will parse the integer part and ignore the rest.