I need to add a number from right to left in the decimal value using javascript [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I am trying to display decimal value in calculator using javascript.
if i click any buttons in the calculator, the button value added to decimal value from the right to left and it should be display in the screen.
For Eg: The default value is 0.00 if i click 2, it should be 0.02 and if i click 3, it should be 0.23 and if i click 4, it should be 2.34 and if i click 5, it should be 23.45 and so on.

You could try:
let number = 0;
// Returns the new value in case you need it to display in console
// and updates the number variable with the new value.
function addNumberRightToLeft(value) {
number = ((number * 10) + (value / 100)).toFixed(2);
return number;
}
console.log(addNumberRightToLeft(5)); // Shows '0.05' in console and updates number variable, so it is now '0.05'.
// or
addNumberRightToLeft(5); // Does not print to console but updates number variable, so it is now '0.55'.
or even use ES6 arrow functions and without side effects (as suggested by Nika):
const addNumberRightToLeft = (p, v) => ((p * 10) + (v / 100)).toFixed(2);
where p is the last value returned and v is what you want to add. In action:
let number = 0;
number = addNumberRightToLeft(number, 5); // 0.05
number = addNumberRightToLeft(number, 5); // 0.55

Like below: resultNum should be first initialize as 0.00;
function showCalc(inputNum)
{
var a = resultNum * 10.00;
var b = inputNum / 100;
resultNum = a + b;
return resultNum;
}

Related

How do I use Javascript to figure out the quantity of 1000s, 100s, 10s, 1s in a number? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 months ago.
Improve this question
Here's an example of what I'm trying to do...
Let's say I have the number 73,284.
The number of thousands is 73 (73,284 divided by 1,000).
The number of hundreds is 2 (284 divided by 100).
The number of tens is 8 (84 divided by 10).
The number of singles is 4 (4 is left).
What I need is a Javascript function that would take the number 73,284 and create 4 numbers from it using the criteria above.
So if the number was 73,284, I'd pass that number into the function as a parameter and the function would return an array that looks like this, [73,2,8,4].
I tried to use the Math.round() function. It seemed to work for the thousands, but not necessarily for the hundreds, tens, and singles.
Simple for loop.
const f = (n) => {
let div = 1000;
const result = [];
for (let i = 0; i < 4 && n; i++, n %= div, div /= 10) {
result.push(Math.floor(n / div));
}
return result;
}
console.log(f(73284));
You can do this by keeping track of how many thousands, hundreds and tens you have and removing these as you go. A little simple arithmetic.
function get(num){
const thousands = Math.floor(num/1000)
const hundreds = Math.floor((num-thousands*1000)/100);
const tens = Math.floor((num-thousands*1000-hundreds*100)/10);
const units = Math.floor(num-thousands*1000-hundreds*100-tens*10)
return [
thousands,
hundreds,
tens,
units
]
}
const [th,hu,te,un] = get(73284)
console.log("Thousands=",th);
console.log("Hundreds=",hu);
console.log("Tens=",te);
console.log("Units=",un);
You will need a combinaison of division with Math.floor and modulo operator (%). The Modulo operator returns the reminder of a division.
Since you will be doing this operation multiple times, this a great opportunity to use recursion. Here is what i've come up with.
First, we need to get how many of a given devider we've got in our input. To do that, you can devide it and ignore the decimal using Math.floor.
const input = 73284
const divider = 1000
const amoutOfDividerInInput = input / divider .
// this returns 73.284, we don't want the .284 so we can use Math.floor.
const amountOfDividerInInputWithoutDecimal = Math.floor(amoutOfDividerInInput)
// we print the value
console.log("there are " + amountOfDividerInInputWithoutDecimal + " 1000s in " + input).
We, then, need to check what is the reminder of that operation, this is where the modulo operator comes in.
const input = 73284
const divider = 1000
const reminderOfTheDivision = input % divider;
// this gives us 284.
We can, then, use this reminder as our new input, and divide the divider by 10, to get how many hundreds are contains in it.
// we devide the divider by 10,
const newDevider = divider / 10;
// we calculate the new amount and reminder
const amoutOfNewDividerInInput = Math.floor(reminderOfTheDivision / newDivider );
const reminderOfTheNewDivision = reminderOfTheDivision % newDivider
// we print the new values
console.log("There are " + amoutOfNewDividerInInput + " 100s in" + input)
And this goes on until we are down to the single digit.
As you can see, there are alot of repetition in this code. A good developer is trying to avoid repetition at all cost. To prevent this, we could use a loop or a recursive function. A recursive function is basically a function that call itself. I've choose to use a function, since it's cleaner.
Here is what i've come up with.
function findDividingQuantity(reminder, divider) {
// if the devider is less than 10, we simply print the reminder.
if(divider < 10) {
console.log('and ' + reminder + ' remains.');
// and we returns to stop the recursion.
return;
}
// otherwise, we get the current amount of the divider in the reminder.
const amount = Math.floor(reminder / divider);
// we then calculate how much is left after the first division,
// this will become our new reminder.
const newReminder = reminder % divider;
// knowing how many of the divider there is in the input, we can print it.
console.log(amount + " " + divider + "s.");
// we call the function again, but with the new reminder
// and the divider divided by 10
findDividingQuantity(newReminder, divider / 10)
}
const input = 73284
console.log("In " + input + " there is: ");
// we call the function with the initial divider: 1000.
findDividingQuantity(input, 1000)
Here is a simple example:
function test(num) {
const arr = num.toLocaleString().split(',');
arr[arr.length-1].toString().split('').map(x=>arr.push(x));
arr[arr.length-4]=0;
return arr.map(x=>+x).filter(x=>x);
}
test(1234); // [1,2,3,4]
test(73284); // [73,2,8,4]
This also works for the millions, and so forth.
Here, we defined a function that will convert the number to localeString and split the number. Next, we loop through the array and convert every element to numbers.

Avoid Number() for scientific notation [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am trying to do the below
Number("0.00000000000122") results in 1.22e-12
But what I need to just that number to get converted from String to Number.
console.log(Number("0.00000000000122"))
You can do it like this:
console.log(Number("0.00000000000122").toFixed(20).replace(/\.?0+$/,""));
Explanation:
toFixed() will keep the number, and replace() will remove trailing zeroes
Edit:
It seems that you want the result of Number("0.00000000000122") to BOTH be a number and also keep it string as "0.00000000000122", not its scientific display.
In that case, you can save it as a number-type variable in ts file, then display it as a string in HTML
If you want to work with precise numbers you have to work with integers.
A Number is not an integer type, it's a float so numbers are represented in memory as a float. The toString method of the number just prints out the value in memory. The integer bit and the dot location.
const scale = 18n;
const digits = 10n ** scale;
const POUND = (number) => BigInt(number) * digits;
const toPound = (number, fraction = false) => {
if (!fraction) {
return String(number / digits);
}
const str = String(number);
if (scale < 1n) {
return str;
}
return `${str.substring(0, Number(BigInt(str.length) - scale))}.${str.substr(-Number(scale))}`;
};
const a = POUND(11000);
const b = POUND(20000);
console.log('scale', String(scale));
console.log('a', toPound(a));
console.log('b', toPound(b));
console.log('mul', toPound((a * b) / digits));
console.log('add', toPound(a + b));
console.log('div', toPound(b / (a / digits), true));
console.log('sub', toPound(b - a));

how to add 1 in last item of array in javascript [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am solving one problem .but getting correct output for small array but my solution fail when array size is large
solution
/**
* #param {number[]} digits
* #return {number[]}
*/
var plusOne = function(digits) {
let str = parseInt(digits.join(''))+1+''
return str.split('')
};
Question
The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.
You may assume the integer does not contain any leading zero, except the number 0 itself.
Example 1:
Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
Example 2:
Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.
above cases are passed
failed cases
Input
[6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3]
Output
[6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,0,0,0]
Expected
[6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,4]
let str = parseInt(digits.join(''))+1+''
With too many array elements, you are simply creating a number that is outside of the integer range here.
An implicit conversion to a float has to happen, and with that you get the inherent loss of precision - which then leads to several zeros in those places at the end, when you reverse the process.
Access the last array element specifically, and add 1 to the value. But if that last element had the value 9 already, you will of course have to repeat that same process for the previous one … basic application of “carry the one”.
var input = [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,9];
var output = [];
// loop over input array in reverse order
for(var i=input.length-1, toadd = 1; i>-1; --i) {
// add value `toadd` to current digit
var incremented = input[i] + toadd;
if(incremented < 10) {
output.unshift(incremented); // add to front of output array
toadd = 0; // reset toadd for all following digits, if we had no overflow
}
else {
output.unshift(0); // overflow occurred, so we add 0 to front of array instead
}
}
console.log(output)
This does take an “overflow” for 9 digits at the end into account; it does not handle the case when all digits are 9 though, if you need to handle that edge case as well, please implement that yourself.
This one recursively checks the last digits:
const test1 = [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3]
const test2 = [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,9]
const plusOne = function(digits) {
if(digits[digits.length - 1] === 9){
digits = [...plusOne(digits.slice(0, -1)), 0]
}else{
digits[digits.length - 1]++
}
return digits;
};
console.log(plusOne(test1));
console.log(plusOne(test2));
You could do something like this :
var arr = [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3,9,9]
function plusOne(index){
if( index < 0 ) return ; // Base case
if(arr[index] === 9){
arr[index] = 0;
plusOne(index-1); // For carry ahead
}else{
arr[index] += 1
}
}
plusOne(arr.length-1) // start with last digit

Algorithm to convert any string to a 1-3 digit number [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I want to make an algorithm, for a NodeJS app, that converta any given string to a 1 to 3 digit number (better if the number is between 1-500).
e.g
ExampleString -> 214
Can anyone help me find a good solution?
EDIT:
I want to get a crime coefficient number from a username (string).
Ok, you can use JS function to get charCode of letter
let str = "some string example";
let sum = 0;
for (let i=0; i<str.length; i++) {
sum += parseInt(str[i].charCodeAt(0), 10); // Sum all codes
}
// Now we have some value as Number in sum, lets convert it to 0..1 value to scale to needed value
let rangedSum = parseFloat('0.' + String(sum)); // Looks dirty but works
let resultValue = Math.round(rangedSum * 500) + 1; // Same alogorythm as using Math.random(Math.round() * (max-min)) + min;
I hope it helps.
So as you are using nodejs, you can use crypto library to get md5 hash of string and then get it as HEX.
const crypto = require('crypto');
let valueHex = crypto.createHash('md5').update('YOUR STRING HERE').digest('hex');
// then get it as decimal based value
let valueDec = parseInt(valueHex, 16);
// and apply the same algorythm as above to scale it between 1-500
function coeficient() {
return Math.floor(Math.random() * 500) + 1;
}
console.log(coeficient());
console.log(coeficient());
console.log(coeficient());

How to Multiply / Sum with Javascript [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
https://jsbin.com/wujusajowa/1/edit?html,js,output
I can sum the numbers of options. Like (5+5+5=15)
But I don't know a way to multiply the input with the sum of selects.
For example, What should I do to do 6 x (5+5+5) and get 90 ?
Use <input type="number">, define a global variable to store value of <input>; attach change event to <input> element to update global variable; use variable at change event of <select> element if variable is defined, else use 1 as multiplier
var input = 0;
$('select').change(function(){
var sum = 0;
$('select :selected').each(function() {
sum += Number($(this).val());
});
$("#toplam").html(sum * (input || 1));
}).change();
$("#miktar").on("change", function() {
input = this.valueAsNumber;
});
jsbin https://jsbin.com/cujohisahi/1/edit?html,js,output
Here's a simple example:
var mySum = 6 * ( 5 + 5 + 5 );
document.getElementById('result').innerHTML = mySum;
<div id="result"></div>

Categories