How to convert a string with mathematical symbols into a number? - javascript

I'm trying to make a calculator with JS. Is there a way to convert a string like var calculation = "11+34*6" into a "number" so JS can print out the solution?

Use eval() function to solve your calculation even it is a string.
let calculation = '11+34*6';
let result = eval(calculation);
document.write(result);
For better understanding read the documentation on Mozilla Developer Network: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval

You can use JavaScript eval function, that allows you to evaluate or execute a string argument, e.g.
console.log(eval("11 + 34 * 6"));

Related

Math Equation Algorithm Javascript

for example, if I had a STRING = "3+3*(4-1)"
if a ran a function and wanted it to solve the equation using javascript, what Would I start with?
Assuming the equation has a correct syntax of javascript, you can use eval to evaluate the value.
i.e.
eval("3+3*(4-1)") = 12

Is using parseInt extraenous if unnecessary?

I am a beginner to coding and JavaScript but I am doing a practice exercise and I came across something I am unsure about.
var nameLength = parseInt(fullName.length);
var nameLength = fullName.length;
I used the first line not even thinking it would already be an integer, so should I still have included the parseInt or not?
Yes, remove var nameLength = parseInt(fullName.length); Below is your explanation:The parseInt() method in JavaScript is used to turn the integer value of a string into an integer. If I have string, say var s = "3";, I could use the + operator to it, but it wouldn't add as if they were numbers (ex. s += 9;, then s would equal "39"). You call the parseInt() method only if you have a value with the type of string. In your case, and in most, if not all languages, the .length or .length() of anything will return an integer. What you're doing is trying to convert a number to a number, which is (after I googled the definition) extraneous.

Trouble converting javascript string to number

I have a script assigns a variable using parseFloat as follows:
var vendorCost = parseFloat(vendorSearchresults[0].getValue('vendorcost')).toFixed(2);
I assumed this would make the variable a number. However when I check it with typeof - it reports it as a string. My solution is as follows:
vendorCost = parseFloat(vendorCost);
Which works, however I'm trying to be more efficient when coding and would like to understand why it doesn't make vendorCost a number when assigning it a number? Is there a way I could make the first statement make vendorCost a number without the need for the second statement? Thanks in advance.
Update - just thought I should mention I'm having the exact same issue without using .toFixed -
var vendorLandedCost = parseFloat(vendorSearchresults[0].getValue('custentity_asg_landed_cost','vendor'));
vendorLandedCost = parseFloat(vendorLandedCost);
The last toFixed() call converts the result of the first parseFloat into a string.
Looks like you need to round the number to two decimal places, which is why you're using the parseFloat call. You can do something like this instead:
vendor_cost = Math.round(parseFloat(vendorSearchresults[0].getValue('vendorcost')) * 100) / 100
Well, Number.toFixed returns string because it is a data presentation function.
See the docs.

Javascript toFixed localized?

Do you know if toFixed is a localized function?
I mean, will this:
var n = 100.67287;
alert(n.toFixed(2));
show "100.67" on english US OS/browsers
and "100,67" (with comma) on Italian OS/browsers?
(Italian or any other local system that uses comma as decimal separator).
Thanks!
Late addition: with Number.toLocaleString() now available on everything bar IE 10 & below, this works, albeit rather long-winded:
var n = 100.67287;
console.log(n.toLocaleString(undefined, {
minimumFractionDigits: 2,
maximumFractionDigits: 2
}));
Using undefined or 'default' for the language code will use the browser default language to format the number.
See developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString for full details.
If you're free to extend the Number prototype, you could defined Number.toLocaleFixed().
No, this will always return a point. The ECMA 262-spec [15.7.4.5] states it should be a point.
You can use this:
var n = 100.67287;
alert(parseFloat(n.toFixed(2)).toLocaleString());
On my german system the result is
100,67
No sadly, there is no real solution in pure jQuery/JavaScript. You'll need Globalize. The problem is that both toFixed() and toLocaleString() take a number and return a string. So you can never use them together. :( If you call foo.toFixed(2).toLocaleString() you won't get the localization (i.e. '1.234' in en should be '1,234' in fr) because its working on the result of toFixed() which is a string, not a number. :(

How to compare locale dependent float numbers?

I need to compare a float value entered in a web form against a range. The problem is that the client computers may have various locale settings, meaning that user may use either "." or "," to separate the integer part from decimal one.
Is there a simple way to do it? As it is for an intranet and that they are only allowed to use IE, a VBScript is fine, even if I would prefer to use JavaScript.
EDIT: Let me clarify it a bit:
I cannot rely on the system locale, because, for example, a lot of our french customers use a computer with an english locale, even if they still use the comma to fill data in the web forms.
So I need a way to perform a check accross multiple locale "string to double" conversion.
I know that the raise condition is "what about numbers with 3 decimal digits", but in our environment, this kind of answer never happen, and if it happens, it will be threated as an out of range error due to the multiplication by a thousand, so it's not a real issue for us.
In Javascript use parseFloat on the text value to get a number. Similarly in VBScript use CDbl on the text value. Both should conform to the current locale settings enforce for the user.
This code should work:
function toFloat(localFloatStr)
var x = localFloatStr.split(/,|\./),
x2 = x[x.length-1],
x3 = x.join('').replace(new RegExp(x2+'$'),'.'+x2);
return parseFloat(x3);
// x2 is for clarity, could be omitted:
//=>x.join('').replace(new RegExp(x[x.length-1]+'$'),'.'+x[x.length-1])
}
alert(toFloat('1,223,455.223')); //=> 1223455.223
alert(toFloat('1.223.455,223')); //=> 1223455.223
// your numbers ;~)
alert(toFloat('3.123,56')); //=> 3123.56
alert(toFloat('3,123.56')); //=> 3123.56
What we do is try parsing using the culture of the user and if that doesn't work, parse it using an invariant culture.
I wouldn't know how to do it in javascript or vbscript exactly though.
I used KooiInc's answer but change it a bit, because it didn't reckon with some cases.
function toFloat(strNum) {
var full = strNum.split(/[.,]/);
if (full.length == 1) return parseFloat(strNum);
var back = full[full.length - 1];
var result = full.join('').replace(new RegExp(back + '$'), '.' + back);
return parseFloat(result);
}
Forbid using any thousands separator.
Give the user an example: "Reals should look like this: 3123.56 or 3123,56". Then simply change , to . and parse it.
You can always tell user that he did something wrong with a message like this:
"I don't understand what you mean by "**,**,**".
Please format numbers like "3123.56."

Categories

Resources