Convert rem to integer value - javascript

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

Related

JavaScript: parseFloat() strips trailing zeros

I have been trying to find a solution to the following problem. I have a string that is a floating-point number like,
var value = '12.30';
When I try to cast it to be a floating number
parseFloat('12.30'); // output is 12.3
I need a way for my logic to return 12.30, the actual value, and that too a number.
Solutions I checked used,
parseFloat('12.30').toFixed(2);
but this converts it to string type and that's not acceptable in my scenario.
Any help would be appreciated. Thanks!
It's not parseFloat()'s fault. Numerically speaking, 12.30 equals 12.3, even if you don't use parseFloat():
const x = 12.30;
console.log(x); // Prints "12.3"
You can just use unary plus from Type Conversions in JavaScript for get number value
var value = '12.30';
alert(parseFloat(value).toFixed(2)); // 12.30
alert(typeof +parseFloat(value).toFixed(2)); // number
Get new successess in development!

Why my session value changed for a particular value?

Can someone help understand why my session value changed for a particular value, 03375?
My MVC controller code:
Session["something"] = "03375";
My view js code:
$(function(){
alert(#Session["something"].ToString());
});
Result: js alerts 1789. Why???
It works for other values except. Here is a fiddle https://dotnetfiddle.net/zLdyO8
This has nothing to do with asp.net session. If you do this in your page
console.log(03375);
You will get 1789
Why is this happening ?
Because when browser's javascript runtime sees a number starting with 0 prefix, it thinks it is octal representation of the number. In fact 03375 is the octal equivalent of 1789. So your browser is basically converting the octal value
to it's decimal equivalent and giving you 1789 (browsers usually parse the number to decimal representation)
From mdn,
Note that decimal literals can start with a zero (0) followed by
another decimal digit, but if every digit after the leading 0 is
smaller than 8, the number gets parsed as an octal number.
This means, if you are trying
console.log(09375);
It will print,9375 !!!
To handle your case, the ideal solution is to set the correct type value. For example, if you are passing a numeric value, simply set the numeric value instead of the string version with leading zero..
Session["something"] = "3375";
Or even better
Session["something"] = 3375;
Then in the client side,
alert(#Session["something"]);
If you absolutely want to keep the 0 prefix, while setting the session value, but you want the value as number at client side, you can read it in a string and then use parseInt to convert it to a number type
var r = '#Session["something"].ToString()';
alert(r); // the string with leading 0
var n = parseInt(r);
alert(n); // the number
alert(typeof(n));

Passing a number to parseFloat() instead of string

In my code, the value of a particular var can originate from any one of a number of different json sources. For some of those sources, the json element concerned will be a string (e.g. "temp": "10.2"), while for other sources the json element will already be a float (e.g. "temp": 10.2).
Does it do any harm (is anything likely to break) if I just pass the json element (from whatever source) through a parseFloat(), even if it's already a float? It seems to work; I'm just thinking about good/bad practice and possible breakage in future or on a different platform.
Thanks.
You should be able to call parseFloat() on a float or a string without any problems. If it is a float already, it's converted to a string first, and then to a float again, so it's a little less efficient, but it shouldn't matter too much.
You should still check the result for NaN, in case there's something unexpected in the data.
The most appropriate method to convert any datatype to a number is to use the Number function:
In a non-constructor context (i.e., without the new operator),
Number can be used to perform a type conversion.
Number("1234") // 1234
Number(1234) // 1234
This method differs from parseFloat in these ways at least:
Number function does not perform "double-conversion" if the input is already a number (ref)
Parse float converts the input to a string then extracts the number (ref)
Number function returns common sense values for most datatypes e.g. Number(true) yields 1
Parse float uses the string value of input so parseFloat(true) tries to parse number from "true" and yields NaN
Number function fails when input string is an invalid number e.g. Number("123abc") yields NaN
Parse float tries to parse as much of a number as possible e.g. parseFloat("123abc") yields 123
If you are sure the value is always a valid number, you should use Number(stringOrNumber).
If you need some additional safety using parseFloat() you could also write your own function which is also performance optimized:
function toFloat(value) {
return typeof value === 'number' ? value : parseFloat(value);
}
I also created a jsPerf test case that shows the performance is >30% better than the plain parseFloat() for a 1:1 ratio between strings and numbers as input values.
Nope there is no problem with passing a number to it
MDN says as long as it can be converted to a number, nothing breaking should happen.
If the first character cannot be converted to a number, parseFloat returns NaN.
As an alternative, you could use the unary operator + which does basically the same thing as parseFloat and also returns NaN if it didn't work.
For instance:
var myFloat = +('10.5');
var myOtherFloat = parseFloat('10.5', 10);
var alreadyAFloat = parseFloat(10.5, 10);
console.log(myFloat === myOtherFloat && myOtherFloat === alreadyAFloat); // true
Wether it's a float or a String using parseFloat() is much safer to avoid all kind of errors.
As you said it will always work, but if you enforce it to be a float you will avoid getting any Exception.
For Example:
Both parseFloat('10.2', 10) and parseFloat(10.2, 10) will work
perfectly and will give you the same result which is 10.2.
Personally I can't see this being a problem what so ever, to be honest I would always use the parsefloat() for one reason, and that is safety. You can never be to sure what may happen, so always predict the worse :D

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;

How to get numerical value from String containing digits and characters

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.

Categories

Resources