how to evaluate this Number("2/4") in JavaScript [duplicate] - javascript

This question already has answers here:
Evaluating a string as a mathematical expression in JavaScript
(26 answers)
Closed 7 years ago.
Hey guys i want to extract/evaluate the answer 2/4 in a string even ehen doing Number ("2/4") it gives me NaN as a result which is fairly reasonable! So my question is how can i evaluate this fraction from a string?

You can do eval("2/4"), which will properly result in 0.5.
However, using eval is a really bad idea...
If you always have a fraction in format A/B, you can split it up and compute:
var s = "11/47";
var ssplit = s.split('/');
document.body.innerText = ssplit[0] / ssplit[1];
Note that Division operator / will implicitly cast strings "11" and "47" to 11 and 47 Numbers.

You are looking for eval. Note
parseFloat("2/4")
2
parseFloat("4/2")
4
eval("4/2")
2
eval("2/4")
0.5

function myFunction() {
var str = "3/4";
var res = str.split("/");
alert(parseFloat(res[0]/res[1]));
}

Try with eval function :
eval("2/4");

Parsing the string only valid for numbers like 0-10 and a decimal (.) and all other if included will then result in NaN.
So, what you can do is like this:
Number(2/4)//0.5
parseFloat(2/4)//0.5
Number('2')/Number('4');//0.5
parseFloat('2')/parseFloat('4');//0.5
Number('2/4');//NaN as / is not parsable string for number
parseFloat('2/4');//2 as upto valid parsable string
parseFloat('1234/4');//1234
So, you can split string then use that like #Yeldar Kurmangaliyev answered for you.

(function(str){
var numbers = str.split("/").map(Number);
return numbers[0] / numbers[1];
})("2/4")
Keep in mind this does not check for invalid input.

Related

Post incrementing a string in javascript [duplicate]

This question already has answers here:
Javascript ++ vs +=1
(3 answers)
Closed 5 years ago.
I was going through exercise problem from Stoyan stefanov book named Object oriented Javascript.
Problem :
var s = 'ls';
s++;
When I execute this in chrome, I get NaN.
For the same code above if I do
var s = 'ls';
s = s+1;
I get output as ls1
Can anyone please explain the reason behind it?
++ tries to convert x as number first. Hence failed because x is having string value and return NaN.
When you do ++ its attempting to increment a number. When you use the + sign, it's either adding or concatenating. Its "smart" and see's that s is a string, so it concatenates it with 1. With ++, you can't increment a string so you get NaN (Not a number)
s++ is an increment operation which is commonly performed for numbers hence the output nan( not a number). In the second case you are doing a concatenation operation. So the ‘ls’ + 1 gives ‘ls1’.
You can't increment strings via ++. That operator is reserved exclusively for the number primitive. Instead Try:
var s = 'ls';
s += 1;
console.log(s);
The above is syntactic sugar for what you originally posted (string concatenation):
s = s + 1;

Extracting float number from string using javascript [duplicate]

This question already has answers here:
how to extract floating numbers from strings in javascript
(3 answers)
Closed 6 years ago.
I have a string in javascript:
ECTS: 7.5 pts
From this string I need to extract 7.5 and parse it to a float value..
I've tried searching, but none of the solutions I found did the trick. I've tried:
var regex = /^\d+\.\d{0,3}$/;
var string = "ECTS: 7.5 pts";
var number = parseFloat(string.match(regex));
console.log("number is: " + number);
I've tried with a couple of different regular expressions, but none of them have done the trick.
I've created this fiddle to illustrate the problem.
EDIT1
I used to have this /\d+/ as my regex, but that didn't include floating point numbers.
EDIT2
I ended up using this as my regex /[+-]?\d+(\.\d+)?/g
Updated fiddle
This works nicely, no need for regex:
var s = "ECTS: 7.5 pts";
var n = parseFloat(s.split(" ")[1]);
$("#test").text(n);
did you try this?
var digits = Number((/(\d+\.\d+)/.exec('ECTS: 7.5 pts') || []).pop());

Effect of x = +x in JavaScript [duplicate]

This question already has answers here:
Coerce to number
(4 answers)
Closed 9 years ago.
Going though the asm.js documentation I've observed this strange (to me at least, quite new to JS) snippet all over the sample code:
function test(x) {
x = +x; // THIS
...
return +(x*y);
}
What is the purpose of the + on the first line?
Its simply used for casting a value with another type to number. Additonally it will return NaN if the value after that + symbol could not get converted into a number.
FIDDLE
From the book Javascript and Jquery - The Missing Maunal
var numOfShoes = '2';
var numOfSocks = 4;
var totalItems = +numOfShoes + numOfSocks;
Adding a + sign before a variable (make sure there’s no space between the two) tells
the JavaScript interpreter to try to convert the string to a number value—if the string
only contains numbers like “2”, you’ll end up with the string converted to a number.
In this example, you end up with 6 (2 + 4). Another technique is to use the Number()
command like this:
var numOfShoes = '2';
var numOfSocks = 4;
var totalItems = Number(numOfShoes) + numOfSocks;
Number() converts a string to a number if possible. (If the string is just letters and not
numbers, you get the NaN value to indicate that you can’t turn letters into a number.)
Perhaps I am reading this wrong but from the specs http://asmjs.org/spec/latest/#parameter-type-annotations
is that casting it as a double?

Javascript Regex for decimals [duplicate]

This question already has answers here:
Simple regular expression for a decimal with a precision of 2
(17 answers)
Closed 9 years ago.
In Javascript, I am trying to validate a user input to be only valid decimals
I have the following JSFiddle that shows the regex I currently have
http://jsfiddle.net/FCHwx/
var regex = /^[0-9]+$/i;
var key = '500.00';
if (key.match(regex) != null) {
alert('legal');
}
else {
alert('illegal');
}
This works fine for integers. I need to also allow decimal numbers (i.e. up to 2 decimal places)
I have tried many of the regex's that can be found on stackoverflow
e.g.
Simple regular expression for a decimal with a precision of 2
but none of them work for this use case
What am I doing wrong?
This should be work
var regex = /^\d+(\.\d{1,2})?$/i;
Have you tried this?
var regex = /^[0-9]+\.[0-9]{0,2}$/i;
I recommend you to not use REGEX for this, but use a simple !isNaN:
console.log(!isNaN('20.13')); // true
console.log(!isNaN('20')); // true
console.log(!isNaN('20kb')); // false
Try this:
\d+(\.\d{1,2})?
d is for digit
d{1,2} is for 1 digit before . and at least 2 digits such as 0.51

JQuery Filter Numbers Of A String [duplicate]

This question already has answers here:
Parsing an Int from a string in javascript
(3 answers)
Closed 9 years ago.
How do you filter only the numbers of a string?
Example Pseudo Code:
number = $("thumb32").filternumbers()
number = 32
You don't need jQuery for this - just plain old JavaScript regex replacement
var number = yourstring.replace(/[^0-9]/g, '')
This will get rid of anything that's not [0-9]
Edit: Here's a small function to extract all the numbers (as actual numbers) from an input string. It's not an exhaustive expression but will be a good start for anyone needing.
function getNumbers(inputString){
var regex=/\d+\.\d+|\.\d+|\d+/g,
results = [],
n;
while(n = regex.exec(inputString)) {
results.push(parseFloat(n[0]));
}
return results;
}
var data = "123.45,34 and 57. Maybe add a 45.824 with 0.32 and .56"
console.log(getNumbers(data));
// [123.45, 34, 57, 45.824, 0.32, 0.56];
Not really jQuery at all:
number = number.replace(/\D/g, '');
That regular expression, /\D/g, matches any non-digit. Thus the call to .replace() replaces all non-digits (all of them, thanks to "g") with the empty string.
edit — if you want an actual *number value, you can use parseInt() after removing the non-digits from the string:
var number = "number32"; // a string
number = number.replace(/\D/g, ''); // a string of only digits, or the empty string
number = parseInt(number, 10); // now it's a numeric value
If the original string may have no digits at all, you'll get the numeric non-value NaN from parseInt in that case, which may be as good as anything.

Categories