Formatting an American Number format to a Integer - javascript

I know I am asking a dull question but at this point of time it is not dull to me.
I have a number say
$123,245,123 in my text box on executing the onBlur function this value is when rounded or done mathematical it is showing as Nan
How will I format this number to a integer.
var value = '$123,245,123'
value = value.Replace?(/[$,]/g, '')
please help in correcting my script to avoid NaN

This should work:
var value = '$123,245,123'
value = parseFloat(value.replace(/[$,]/g, ''));

try Number('$123,245,123'.replace(/[$,]/g, '')).
That's: replace (lowercase r), without ?
Using Number-conversion, values like '$123,245,123.23' are also converted (to float)
Instead of Number, a simple + is equivalent: +('$123,245,123'.replace(/[$,]/g, ''))
If you need a check for NaN, use something like:
var dollarvalue = +('$123,245,123'.replace(/[$,]/g, '')) || 0;
If you only want to keep the dollar value (no cents, integer), use
(+('$123,245,123.43'.replace(/[$,]/g, ''))).toFixed(0);
If you want to round the dollar value, use
Math.round(+('$123,245,123.43'.replace(/[$,]/g, '')));

Related

Convert rem to integer value

I am trying to pull out a rem value to an integer.
this.props.viewTitleContainerStyle.paddingTop
Above line of code gives me a value of 1.00rem in the debugger. The viewTitleContainerStyle is stored as theme.sizes.Measures.Measure100. I need to convert this to an integer value for a comparison in another expression. Any way to get this?
I tried parseInt but did not work.
You can use parseInt or parseFloat precisely for this. It will parse numbers until it sees an invalid number (i.e. rem), at which point it will stop parsing and return you the valid int or float, whichever you asked for. The difference in the two is whether you want it to stop parsing when it sees a . or if you want the digits after the decimal to be included.
var value = "1.25rem";
var intParsed = parseInt(value);
var floatParsed = parseFloat(value);
console.log("parseInt():", intParsed);
console.log("parseFloat():", floatParsed);

How to get an 8 decimal output?

I am trying to get an 8 decimal output from the following function.
The following function multiplies an input by 2 and then updates this input with the wagerUpdate variable. I would like this outputted number to have 8 decimal places.
For example: if input number is 0.00000001 (this code is for a bitcoin website), then I would like output number to be 0.00000002. For some reason the code below is not working properly as the output number is in the format of 2e-8 without the .toFixed(8) code. Please help if you are able to. Thank you so much.
<script>
function MultiplyWagerFunction() {
var wager = document.getElementById("wagerInputBox").value;
var wagerUpdate = wager*2;
document.getElementById("wagerInputBox").value = +wagerUpdate.toFixed(8);
}
</script>
If you remove the + before wagerUpdate.toFixed(8) it should work fine. wagerUpdate has already be converted to a number when you multiplied it by 2 so there should be no need for the unary +
var a = "0.00000001";
var b = a*2;
console.log(b.toFixed(8));
console.log(+b.toFixed(8));
^ see the difference.
The reason it doesn't work is because what you are doing is equivalent to:
+(b.toFixed(8))
because of the precedence of the operators (member access . is higher than unary +). You are converting b to a string with .toFixed and then converting it back into a number with + and then converting it back into a string again! (this time with the default toString behavior for numbers giving you exponential notation)
Just remove + from +wagerUpdate.toFixed(8); and you would be good.
Instead of:
document.getElementById("wagerInputBox").value = +wagerUpdate.toFixed(8);
try:
document.getElementById("wagerInputBox").innerHTML = +wagerUpdate.toFixed(8);
Why I say so is may be when you set value, browser tries to convert to best possible outcome. But, inner HTML should take the string equivalent!

How can I remove all decimals from a JavaScript variable?

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, '')))

Javascript parseInt not working on a string, trying to get an integer from an HTML value

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;

Javascript convert string to integer

I am just dipping my toe into the confusing world of javascript, more out of necessity than desire and I have come across a problem of adding two integers.
1,700.00 + 500.00
returns 1,700.00500.00
So after some research I see that 1,700.00 is being treated as a string and that I need to convert it.
The most relevant pages I read to resolve this were this question and this page. However when I use
parseInt(string, radix)
it returns 1. Am I using the wrong function or the an incorrect radix (being honest I can't get my head around how I decide which radix to use).
var a="1,700.00";
var b=500.00;
parseInt(a, 10);
Basic Answer
The reason parseInt is not working is because of the comma. You could remove the comma using a regex such as:
var num = '1,700.00';
num = num.replace(/\,/g,'');
This will return a string with a number in it. Now you can parseInt. If you do not choose a radix it will default to 10 which was the correct value to use here.
num = parseInt(num);
Do this for each of your string numbers before adding them and everything should work.
More information
How the replace works:
More information on replace at mdn:
`/` - start
`\,` - escaped comma
`/` - end
`g` - search globally
The global search will look for all matches (it would stop after the first match without this)
'' replace the matched sections with an empty string, essentially deleting them.
Regular Expressions
A great tool to test regular expressions: Rubular and more info about them at mdn
If you are looking for a good tutorial here is one.
ParseInt and Rounding, parseFloat
parseInt always rounds to the nearest integer. If you need decimal places there are a couple of tricks you can use. Here is my favorite:
2 places: `num = parseInt(num * 100) / 100;`
3 places: `num = parseInt(num * 1000) / 1000;`
For more information on parseInt look at mdn.
parseFloat could also be used if you do not want rounding. I assumed you did as the title was convert to an integer. A good example of this was written by #fr0zenFry below. He pointed out that parseFloat also does not take a radix so it is always in base10. For more info see mdn.
Try using replace() to replace a , with nothing and then parseFloat() to get the number as float. From the variables in OP, it appears that there may be fractional numbers too, so, parseInt() may not work well in such cases(digits after decimal will be stripped off).
Use regex inside replace() to get rid of each appearance of ,.
var a = parseFloat('1,700.00'.replace(/,/g, ''));
var b = parseFloat('500.00'.replace(/,/g, ''));
var sum = a+b;
This should give you correct result even if your number is fractional like 1,700.55.
If I go by the title of your question, you need an integer. For this you can use parseInt(string, radix). It works without a radix but it is always a good idea to specify this because you never know how browsers may behave(for example, see comment #Royi Namir). This function will round off the string to nearest integer value.
var a = parseInt('1,700.00'.replace(/,/g, ''), 10); //radix 10 will return base10 value
var b = parseInt('500.00'.replace(/,/g, ''), 10);
var sum = a+b;
Note that a radix is not required in parseFloat(), it will always return a decimal/base10 value. Also, it will it will strip off any extra zeroes at the end after decimal point(ex: 17500.50 becomes 17500.5 and 17500.00 becomes 17500). If you need to get 2 decimal places always, append another function toFixed(decimal places).
var a = parseFloat('1,700.00'.replace(/,/g, ''));
var b = parseFloat('500.00'.replace(/,/g, ''));
var sum = (a+b).toFixed(2); //change argument in toFixed() as you need
// 2200.00
Another alternative to this was given by #EpiphanyMachine which will need you to multiply and then later divide every value by 100. This may become a problem if you want to change decimal places in future, you will have to change multiplication/division factor for every variable. With toFixed(), you just change the argument. But remember that toFixed() changes the number back to string unlike #EpiphanyMachine solution. So you will be your own judge.
try this :
parseFloat(a.replace(/,/g, ''));
it will work also on : 1,800,300.33
Example :
parseFloat('1,700,800.010'.replace(/,/g, '')) //1700800.01
Javascript doesn't understand that comma. Remove it like this:
a.replace(',', '')
Once you've gotten rid of the comma, the string should be parsed with no problem.

Categories

Resources