JavaScript Calculator - scope? - javascript

I am relatively new to JS, and trying to create a JavaScript calculator that takes a number and then uses the operator with a second number to create a total. Then I could use another operator on that total with another number, and so on, until the clear button is pressed. My biggest problem seems to be with the scope of my variables. At the moment I created a stopgap, that will add and subtract one digit numbers. Is there a reason why this code won't at least multiply and divide single numbers?
My other idea is to create two variables with empty arrays for the two numbers that will be used, so that as each active button is pressed you can push it into the specific array, which I think would solve the problem of only using single digit numbers, right? Thanks in advance! Just trying to learn and keep getting better!
// Calculator
var number = '';
var newNumber = '';
var operator = '';
var totalVal = '';
var result = '';
var inputCount = 0;
// Adds clicked numbers to the number variable and then sets value to totalVal
$('.numbers').on('click', function(){
if(result == ''){
inputCount++;
if (inputCount < 2){
number += $(this).text();
$('.inner-screen').text(number);
result = number;
console.log("number: " + number);
console.log("result: " + result);
} else {
newNumber = $(this).text();
}
// number = '';
} else{
newNumber += $(this).text();
$('.inner-screen').text(newNumber);
}
console.log("number: " + number + ", newNumber: " + newNumber);
});
$('.operators').on('click', function(){
operator = $(this).text();
console.log(operator);
$('.inner-screen').text('');
});
// Resets all the variables when clear button is clicked
$('.clear').on('click', function(){
number = '';
result = '';
newNumber = '';
operator = '';
totalVal = '';
inputCount = 0;
console.log('Clear Button Worked!');
$('.inner-screen').text('');
});
$('.eval').on('click', function(){
console.log("num1: " + number + ", operator: " + operator + ", num2: " + newNumber);
if (operator === " + "){
result = parseFloat(newNumber) + parseFloat(number);
console.log(result);
} else if (operator === " - "){
result = parseFloat(number) - parseFloat(newNumber);
console.log(totalVal);
} else if (operator === " X "){
result = parseFloat(newNumber) * parseFloat(number);
console.log(result);
} else if (operator === " / "){
result = parseFloat(number) / parseFloat(newNumber);
console.log(result);
} else {
console.log("didn't catch");
}
$('.inner-screen').text(result);
number = '';
newNumber = '';
});

Is there a reason why this code won't at least multiply and divide single numbers?
Right-o. I see what's going on.
Once you've pressed eval, you need to remember some state:
number = result;
result = '';
newNumber = '';
operator = '';
inputCount = 1;
Old version:
http://jsfiddle.net/xjegrp58/
New version, with state added to the eval function:
http://jsfiddle.net/axLhcawf/
Try this on each:
2 * 2 = 4, then * 2 to get 8

Related

user input output multiplication table

I need to make a multiplication table that displays the users input from 1-9, so if they enter 3 it will display the multiplication table for 3 from 1-9. it must do this with each number.
I have a for loop working for only 1 number and I dont know what else to do, I'm still really new to this so I'm not sure how to make it work for me.
prompt ("please enter a number");
var a = 1;
var b;
for (var i = 1; i <= 9; i++){
b= a*i
document.write("" + a + "*" + i + "=", + b +"<br>");
}
If I enter any number from 1-9 it must display the multiplication from 1-9 for that one number. Must work for each number entered.
the variable a should have the value received from the prompt and not 1
var a = prompt ("please enter a number");
var b;
for (var i = 1; i <= 9; i++){
b= a*i
document.write("" + a + "*" + i + "=", + b +"<br>");
}
You need to create variable for the prompt and add it inside your document.write
var question = prompt("please enter a number");
var a = 1;
var b;
for (var i = 1; i <= 9; i++) {
b = a * i
document.write(question + " " + "* " + i + " " + " = ", + b + "<br>");
}
You have to assign the return of the prompt function to your a variable.
Also, you have to cast this string value to a number to make sure your calculations are correct.
In the snippet below:
I wrapped the call to prompt with the Number function to get a number (MDN doc about Number).
I changed the var keywords to let and const as this is preferred over var, which declares global variables.
I replaced the string concatenation with a template string, which is easier to read when building complex strings (MDN doc on template literals).
const a = Number(prompt('please enter a number'));
for (let i = 1; i <= 9; i++) {
const b = a * i;
document.write(`${a} * ${i} = ${b}<br>`);
}

Internationally pretty print string objects that contain decimals

I am using MikeMcl's big.js for precise accounting which outputs a string when calling toFixed().
I'd like to pretty print decimal results in an internationally aware way much like how the Date Object can automatically print dates and times in a local format.
Is there a way to format string objects that contain decimals internationally?
var myNumber = 123456.78;
console.log(myNumber.toLocaleString());
This should do the job.
function localize(fixed) {
/*Determine decimal symbol and digit grouping symbol.*/
var decimalSymbol = '.';
var digitGroupingSymbol = ',';
var dummy = 1234.5;
testResult = dummy.toLocaleString();
/*Browsers using digit grouping symbol.*/
if (testResult.length === 7) {
decimalSymbol = testResult[5];
digitGroupingSymbol = testResult[1];
}
/*Browsers not using digit grouping symbol.*/
if (testResult.length === 6) {
decimalSymbol = testResult[4];
digitGroupingSymbol = (decimalSymbol === '.'? ',': '.');
}
/*Format the number.*/
var result = '';
var dsIndex = fixed.indexOf('.');
if (dsIndex < 0) {
throw new Error('Expected decimal separator \'.\' in "' + fixed + '".');
}
for (var i = 0; i < dsIndex; ++i) {
if (fixed[i] < '0' || fixed[i] > '9') {
throw new Error('Expected digit, got "' + fixed[i] + '".');
}
if (i > 0 && i%3 === dsIndex%3) result += digitGroupingSymbol ;
result += fixed[i];
}
result += decimalSymbol + fixed.substr(dsIndex + 1);
return result;
}
/*Demonstration*/
var n1 = '123.4567890';
console.assert(localize(n1));
var n2 = '1234.567890';
console.log(localize(n2));
var n3 = '123456789012345678.1234567890';
console.log(localize(n3));
var n4 = '1234567890123456789.1234567890';
console.log(localize(n4));
var n5 = '12345678901234567890.1234567890';
console.log(localize(n5));
Output:
123.4567890
1.234.567890
123.456.789.012.345.678.1234567890
1.234.567.890.123.456.789.1234567890
12.345.678.901.234.567.890.1234567890

Adding a comma at every third number character

In my code I have a variable myCash, which is printed into an h1 element using javaScript's innerHTML. I found a function online that puts a comma after every third character from the end of the number so that the number is easier to read. I've tried for a couple of hours now sending my variable myCash into the function and then print it on the screen. I CANNOT get it to work.
I've tried just alerting the new variable to the screen after page load or by pressing a button, but I get nothing and the alert doesn't even work. Here's the comma insert function:
function commaFormatted(amount) {
var delimiter = ","; // replace comma if desired
amount = new String(amount);
var a = amount.split('.',2)
var d = a[1];
var i = parseInt(a[0]);
if(isNaN(i)) { return ''; }
var minus = '';
if(i < 0) { minus = '-'; }
i = Math.abs(i);
var n = new String(i);
var a = [];
while(n.length > 3)
{
var nn = n.substr(n.length-3);
a.unshift(nn);
n = n.substr(0,n.length-3);
}
if(n.length > 0) { a.unshift(n); }
n = a.join(delimiter);
if(d.length < 1) { amount = n; }
else { amount = n + '.' + d; }
amount = minus + amount;
return amount;
}
now when I want my variable to change I've tried it a few different ways including this:
var newMyCash = commaFormatted(myCash);
alert(newMyCash);
and this:
alert(commaFormatted(myCash);
Where of course myCash equal some large number;
This does absolutely nothing! What am I doing wrong here??
Also,
Try this as a drop in replacement and try alerting the response:
http://phpjs.org/functions/number_format:481
Do you see any errors in the console of your browser (usually f12)?
This is not my function, but I hope it helps you.
function addCommas(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
Usage:
var newMyCash = addCommas( myCash ); alert( newMyCash );
Source: http://www.mredkj.com/javascript/nfbasic.html
You are most likely not passing in a number that contains a decimal, which the function expects.
Working Demo

how to get formatted integer value in javascript

This is my integer value
12232445
and i need to get like this.
12,232,445
Using prototype how to get this?
var number = 12232445,
value = number.toString(),
parts = new Array;
while (value.length) {
parts.unshift(value.substr(-3));
value = value.substr(0, value.length - 3);
}
number = parts.join(',');
alert(number); // 12,232,445
It might not be the cleanest solution, but it'll do:
function addCommas(n)
{
var str = String(n);
var result = '';
for(var i = 0; i < str.length; i++)
{
if((i - str.length) % 3 == 0)
result += ',';
result += str[i];
}
return result;
}
Here is the function I use, to format thousands separators and takes into account decimals if any:
function thousands(s) {
var rx = /(-?\d+)(\d{3})/,
intDec = (''+s)
.replace(new RegExp('\\' + $b.localisation.thousandSeparator,'g'), '')
.split('\\' + $b.user.localisation.decimalFormat),
intPart = intDec[0],
decPart = intDec[1] || '';
while (rx.test(intPart)) {
intPart = intPart.replace(rx,'$1'+$b.localisation.thousandSeparator+'$2');
}
return intPart + (decPart && $b.localisation.decimalFormat) + decPart;
}
thousands(1234.56) //--> 1,234.56
$b.localisation is a global variable used for the session.
$b.localisation.thousands can have the values , or . or a space.
And $b.localisation.decimalFormat can have the values , or . depending on the locale of the user

How do I convert an integer to decimal in JavaScript?

I have a number in JavaScript that I'd like to convert to a money format:
556633 -> £5566.33
How do I do this in JavaScript?
Try this:
var num = 10;
var result = num.toFixed(2); // result will equal string "10.00"
This works:
var currencyString = "£" + (amount/100).toFixed(2);
Try
"£"+556633/100
This script making only integer to decimal.
Seperate the thousands
onclick='alert(MakeDecimal(123456789));'
function MakeDecimal(Number) {
Number = Number + "" // Convert Number to string if not
Number = Number.split('').reverse().join(''); //Reverse string
var Result = "";
for (i = 0; i <= Number.length; i += 3) {
Result = Result + Number.substring(i, i + 3) + ".";
}
Result = Result.split('').reverse().join(''); //Reverse again
if (!isFinite(Result.substring(0, 1))) Result = Result.substring(1, Result.length); // Remove first dot, if have.
if (!isFinite(Result.substring(0, 1))) Result = Result.substring(1, Result.length); // Remove first dot, if have.
return Result;
}
Using template literals you can achieve this:
const num = 556633;
const formattedNum = `${num/100}.00`;
console.log(formattedNum);

Categories