Dice values still concatenating after using parseInt/parseFloat - javascript

I am new to javascript and i'm trying to add values from a thrown dice using the click event listener. I have tried using parseInt/parseFloat to sum the numbers and show the values using inner.html but they keep concatenating. Here's my code
const dice=document.getElementsByClassName("btn-roll")[0];
let diceImg=document.querySelector("#dice-1");
let diceImg2=document.querySelector("#dice-2");
let p1CurrentScore=document.getElementById("current-0");
dice.addEventListener("click",function(){
let random1=Math.floor(Math.random()* 6) +1;
let random2=Math.floor(Math.random()* 6) +1;
diceImg.src="dice-" + random1 +".png";
diceImg2.src="dice-" + random2 +".png";
let totalDice=random1+random2;
let total=0;
total= total + (p1CurrentScore.innerHTML+=totalDice);
parseInt(total);
})

There is no need to create a total variable since that value is being stored in p1CurrentScore.innerHTML. What you want to do is set p1CurrentScore.innerHTML equal to its previous value plus totalDice.
Ultimately you want your listener to look something like the following:
dice.addEventListener("click",function(){
let random1=Math.floor(Math.random()* 6) +1;
let random2=Math.floor(Math.random()* 6) +1;
diceImg.src = "dice-" + random1 + ".png";
diceImg2.src = "dice-" + random2 + ".png";
let totalDice=random1+random2;
p1CurrentScore.innerHTML=parseInt(p1CurrentScore.innerHTML) + totalDice
})
Here is an example: https://470290.playcode.io

You should use parseInt to transform the text before you use the text in a math operation.
Like this:
const dice=document.getElementsByClassName("btn-roll")[0];
let diceImg=document.querySelector("#dice-1");
let diceImg2=document.querySelector("#dice-2");
let p1CurrentScore=document.getElementById("current-0");
dice.addEventListener("click",function(){
let random1 = Math.floor(Math.random()* 6) +1;
let random2 = Math.floor(Math.random()* 6) +1;
diceImg.src = "dice-" + random1 + ".png";
diceImg2.src = "dice-" + random2 + ".png";
let totalDice = random1 + random2;
let total = 0;
total = total + (parseInt(p1CurrentScore.innerHTML) += totalDice); // -> Use parseInt before the operation
// parseInt(total); -> Not necessary
})

Value of p1CurrentScore.innerHTML is a string and when you sum it, concatenating will be done and you get string as a result. Remember that when you are summing string and number you get concatenated string. So you need to parse that:
total= total + ((parseInt(p1CurrentScore.innerHTML))+=totalDice);
On the other hand if you subtract number from string which value is number it will be automatically converted to number. So you could do also something like (p1CurrentScore.innerHTML-0).
I hope this helps.

Related

JavaScript increment of the the last decimal number

I'm trying to to increment the last decimal of a number from 1.234 to 1.235
var numb = 1.234;
numb.replace(/\d$/, numb + 1);
or let just say that the problem is like following
var oNumber = 1.34567
var oDecimalCount = 5
increaseNumber(oNumber, oDecimalCount){
oNumber += //increase the 5th(oDecimalCount) decimal place
}
You could do this :
count the numbers after the decimal point
use this number to remove the decimal point * 10^n
add 1
use the number to place the decimals back in place / 10^n
//I found this function here : https://www.tutorialspoint.com/decimal-count-of-a-number-in-javascript
const decimalCount = num => {
// Convert to String
const numStr = String(num);
// String Contains Decimal
if (numStr.includes('.')) {
return numStr.split('.')[1].length;
};
// String Does Not Contain Decimal
return 0;
}
let numb = 1.234;
let count = decimalCount(numb);
console.log(((numb * 10 ** count) + 1) / 10 ** count);
Im not sure I understand the question completely, but can't you just do it like this
let numb = 1.234;
numb += 0.001;

Usng jquery need to create division sums without remainders

In my current project, I am creating random mathematics questionnaires for abacus student. So the exam page will serve sums one by one. Based on the student level I am generationg sums at front end using jquery and rendering to get student answer for validation. In a particular level I need to generate divisions with zero remainder.
So, I am using below function to generate the sum which is returning undefined sometimes.
tripleDigitSingleDigitWithoutRemainder: function()
{
var dividend = BOBASSESSMENT.general.randomIntFromInterval(100, 999);
var divisor = BOBASSESSMENT.general.randomIntFromInterval(2, 9);
console.log("out: " + dividend + "_" + divisor);
console.log("remainder: " + (dividend % divisor));
var result_val = "";
// result_val = dividend % divisor;
if(dividend % divisor != 0)
{
console.log('loop_again');
BOBASSESSMENT.general.tripleDigitSingleDigitWithoutRemainder();
}else{
result_val = dividend + "_" + divisor;
console.log("return: " + result_val);
}
console.log("final_return: " + result_val);
return result_val;
}
hence, please help me here to do further.
the requirement is to show question one by one and I need a dividend value and divisor value which does give remainder as 0. It means 16 % 2 = 0 not like 16 % 3 = 1.
Can you please some one help here.
As discussed in the comments here's a way to use a loop to try again with different values instead of recursion:
tripleDigitSingleDigitWithoutRemainder: function()
{
for(;;)
{
var dividend = BOBASSESSMENT.general.randomIntFromInterval(100, 999);
var divisor = BOBASSESSMENT.general.randomIntFromInterval(2, 9);
if(dividend % divisor == 0)
{
var result_val = dividend + "_" + divisor;
console.log("return: " + result_val);
return result_val;
}
}
}
Here we have an infinite loop and we keep looping until we have a valid problem and then immediately return when we do. for(;;) is one way of writing an infinite loop: there are others e.g. while (true) { ... } if that's clearer - up to you.
(However I prefer the approach in Wimanicesir's answer which constructs a correct value rather than just trying repeatedly until we find one, which may take many more goes.)
As said in the comments. Isn't it better to just create a working division by creating it with a product?
function generate() {
// Numbers [2-9]
var small = Math.floor(Math.random() * 8) + 2
// This will give the limit of current divider
var limit = Math.ceil(900 / small)
// We check the minimum now
var minimum = Math.floor(100 / small)
// We create a new random with given limit
var big = Math.ceil(Math.random() * limit) + minimum
// Create the product
var product = big * small;
return { question: product + ' / ' + small, answer: big }
}
console.log(generate())

Javascript | How to split one semi-random number into three random numbers, whose additive value add to initial number

My goal: Given a specific rgb value such as (215, 183, 71), I want to generate a random number between 20-30, and divide that number into three additive parts that add to the initial number. From there, each number should be subtracted from their respective color value, from a specified color.
Unless I'm lacking a significant amount of brainpower currently, this seems like it requires a somewhat creative solution, which is why I leave it in the hands of whomever may read this.
E.G:
var colorDifference=27;
var RGB=rgb(100-differenceR,100-differenceG,100-differenceB,1);
function colorDiffValues(){
differenceR=5;
differenceG=13;
differenceB=9;
}
However, clearly not with those exact value. so it would have to be something such as
var colorDiff= random number between 20 to 30
var RGB=rgb(r-diffR, g-diffG,b-diffB);
function colorDiffValues(){
diffR= random value
diffG= random value
diffB= random value
// where diffR+diffG+diffB=colorDiff
// AND diffR,diffG, and diffB are all positive numbers.
}
goodnight!!
This is the relevant logic that would split a random value intro three random values. You only need to specify what is the minimum value for each of the three numbers.
<script>
// get random number between 20 and 30
let colorDifference = 20 + Math.floor(Math.random() * 11);
// defines the smallest value for each of the generated numbers
// if set to 3, then 25 split into 10, 2, 13 wouldn't be valid as one of them is lower than 3
let smallestValue = 3;
// generate numbers
let totalRange = colorDifference;
let numberOne = smallestValue + Math.floor(Math.random() * (totalRange - 3*smallestValue));
totalRange -= numberOne;
let numberTwo = smallestValue + Math.floor(Math.random() * (totalRange - 2*smallestValue));
let numberThree = colorDifference - (numberOne + numberTwo);
console.log('Value ' + colorDifference + ' was split into ' + numberOne + ',' + numberTwo + ', ' + numberThree);
</script>
Here you have an example where I use it to paint a div with a random color:
<div class="box" id="original"></div>
<div class="box" id="generated"></div>
<span id="result"></span>
<style>
.box{
width:100px;
height:100px;
border:1px solid #000;
}
</style>
<script>
// values for original
let red = 200;
let green = 200;
let blue = 200;
// get random number between 20 and 30
let colorDifference = 20 + Math.floor(Math.random() * 11);
// defines the smallest value for each of the generated numbers
// if set to 3, then 25 split into 10, 2, 13 wouldn't be valid as one of them is lower than 3
let smallestValue = 3;
// generate numbers
let totalRange = colorDifference;
let numberOne = smallestValue + Math.floor(Math.random() * (totalRange - 3*smallestValue));
totalRange -= numberOne;
let numberTwo = smallestValue + Math.floor(Math.random() * (totalRange - 2*smallestValue));
let numberThree = colorDifference - (numberOne + numberTwo);
// generate colors
let newRed = red - numberOne;
let newGreen = green - numberTwo;
let newBlue = blue - numberThree;
// set colors
document.getElementById('result').innerHTML = colorDifference + ' split into ' + numberOne + ', ' + numberTwo + ', ' + numberThree;
document.getElementById('original').style.backgroundColor = 'rgba('+red+','+green+','+blue+',1)';
document.getElementById('generated').style.backgroundColor = 'rgba('+newRed+','+newGreen+','+newBlue+',1)';
</script>

Javascript not displaying strings with " ' " in them

I am writing a Javascript function where strings with apostrophe ( ' ) are not being displayed. Is there a way I can go around this? The below function assumes x is a string.
function addItem(x, y) //adds item on screen and adds Total
{
var newRow = "<tr><td>"+x+"</td><td>€"+y.toFixed(2)+"</td><td><input type=\"button\" onclick=\"subtract("+y+")\" value = \"X\"></td></tr>"
$('#order').append(newRow);
document.getElementById("currentorder").value += newRow;
//Adds Total Value
var total = document.getElementById('price').innerHTML;
total = parseFloat(total);
var z = +y + +total;
document.getElementById('price').innerHTML=z.toFixed(2);
event.preventDefault();
}
Confusing Addition Operators
The following line looks quite a bit off :
var z = +y + +total;
If you just want to add y and total, just simplify it as :
var z = y + total;
Consider Possible Parsing Errors
Another idea would be to consider stripping out any non float related characters (i.e. non decimals and digits) within your string prior to calling your parseFloat() function :
var total = parseFloat(document.getElementById('price').innerHTML.replace(/[^\d\.]/g,''));

generate 4 digit random number using substring

I am trying to execute below code:
var a = Math.floor(100000 + Math.random() * 900000);
a = a.substring(-2);
I am getting error like undefined is not a function at line 2, but when I try to do alert(a), it has something. What is wrong here?
That's because a is a number, not a string. What you probably want to do is something like this:
var val = Math.floor(1000 + Math.random() * 9000);
console.log(val);
Math.random() will generate a floating point number in the range [0, 1) (this is not a typo, it is standard mathematical notation to show that 1 is excluded from the range).
Multiplying by 9000 results in a range of [0, 9000).
Adding 1000 results in a range of [1000, 10000).
Flooring chops off the decimal value to give you an integer. Note that it does not round.
General Case
If you want to generate an integer in the range [x, y), you can use the following code:
Math.floor(x + (y - x) * Math.random());
This will generate 4-digit random number (0000-9999) using substring:
var seq = (Math.floor(Math.random() * 10000) + 10000).toString().substring(1);
console.log(seq);
I adapted Balajis to make it immutable and functional.
Because this doesn't use math you can use alphanumeric, emojis, very long pins etc
const getRandomPin = (chars, len)=>[...Array(len)].map(
(i)=>chars[Math.floor(Math.random()*chars.length)]
).join('');
//use it like this
getRandomPin('0123456789',4);
$( document ).ready(function() {
var a = Math.floor(100000 + Math.random() * 900000);
a = String(a);
a = a.substring(0,4);
alert( "valor:" +a );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
Your a is a number. To be able to use the substring function, it has to be a string first, try
var a = (Math.floor(100000 + Math.random() * 900000)).toString();
a = a.substring(-2);
You can get 4-digit this way .substring(startIndex, length), which would be in your case .substring(0, 4). To be able to use .substring() you will need to convert a to string by using .toString(). At the end, you can convert the resulting output into integer by using parseInt :
var a = Math.floor(100000 + Math.random() * 900000)
a = a.toString().substring(0, 4);
a = parseInt(a);
alert(a);
https://jsfiddle.net/v7dswkjf/
The problem is that a is a number. You cannot apply substring to a number so you have to convert the number to a string and then apply the function.
DEMO: https://jsfiddle.net/L0dba54m/
var a = Math.floor(100000 + Math.random() * 900000);
a = a.toString();
a = a.substring(-2);
$(document).ready(function() {
var a = Math.floor((Math.random() * 9999) + 999);
a = String(a);
a = a.substring(0, 4);
});
// It Will Generate Random 5 digit Number & Char
const char = '1234567890abcdefghijklmnopqrstuvwxyz'; //Random Generate Every Time From This Given Char
const length = 5;
let randomvalue = '';
for ( let i = 0; i < length; i++) {
const value = Math.floor(Math.random() * char.length);
randomvalue += char.substring(value, value + 1).toUpperCase();
}
console.log(randomvalue);
function getPin() {
let pin = Math.round(Math.random() * 10000);
let pinStr = pin + '';
// make sure that number is 4 digit
if (pinStr.length == 4) {
return pinStr;
} else {
return getPin();
}
}
let number = getPin();
Just pass Length of to number that need to be generated
await this.randomInteger(4);
async randomInteger(number) {
let length = parseInt(number);
let string:string = number.toString();
let min = 1* parseInt( string.padEnd(length,"0") ) ;
let max = parseInt( string.padEnd(length,"9") );
return Math.floor(
Math.random() * (max - min + 1) + min
)
}
I've created this function where you can defined the size of the OTP(One Time Password):
generateOtp = function (size) {
const zeros = '0'.repeat(size - 1);
const x = parseFloat('1' + zeros);
const y = parseFloat('9' + zeros);
const confirmationCode = String(Math.floor(x + Math.random() * y));
return confirmationCode;
}
How to use:
generateOtp(4)
generateOtp(5)
To avoid overflow, you can validate the size parameter to your case.
Numbers don't have substring method. For example:
let txt = "123456"; // Works, Cause that's a string.
let num = 123456; // Won't Work, Cause that's a number..
// let res = txt.substring(0, 3); // Works: 123
let res = num.substring(0, 3); // Throws Uncaught TypeError.
console.log(res); // Error
For Generating random 4 digit number, you can utilize Math.random()
For Example:
let randNum = (1000 + Math.random() * 9000).toFixed(0);
console.log(randNum);
This is quite simple
const arr = ["one", "Two", "Three"]
const randomNum = arr[Math.floor(Math.random() * arr.length)];
export const createOtp = (): number => {
Number(Math.floor(1000 + Math.random() * 9000).toString());
}

Categories