find the number of a digit can exist in another number - javascript

I have a number and a master number. How do I check how many times can x exist in the number?
const x = 2
const masterNumber = 5
so here, 2 can exist 2 times in 5. i.e. 2+2 < 5.
const x = 3
const masterNumber = 5
here, 3 exist once. cos 3+3> 5.
const x = 1
const masterNumber = 5
can exist 5 times. cos 1+1+1+1+1=5
I considered doing masterNumber / x but for e.g. for x=2, it returns 2.5

Use Math.floor():
const x = 3;
const masterNumber = 5;
var numTimes = Math.floor(masterNumber / x);
console.log(numTimes);
The floor of the quotient will, by definition, be the number of times the whole integer denominator can fit into the numerator, excluding the fractional remainder.

You need to round down that number using Math.floor:
$('#x, #master').change(function () {
let result = parseInt($('#master').val()) / parseInt($('#x').val());
let finalResult = Math.floor(result);
console.log(result, finalResult);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
X: <input type="number" id="x"/><br/>
Master number: <input type="number" id="master"/>

Related

How to verify if a number has at most N decimal places?

How to verify if an input type number contains a maximum of 3 decimals, without using regex?
let x = 1.5555
let y = 1.55
x is false
y is true
You can use a formula like:
(x * 10**N) % 1 === 0
Here x is your number that potentially contains decimals (eg: 1.555) and N is the maximum amount of decimal places you want to allow for.
Eg, for numbers with 3 (N = 3) or fewer decimal places, you will get x*1000, which will evaluate to an integer. Eg:
1.55 -> 1550
1.555 -> 1555
For numbers with more than 3 decimal places, doing x*1000 won't convert it to an int, it will only shift parts of the number over:
1.5555 -> 1555.5 // still a decimal
The % 1 check then gets the remainder of the above number if it was to be divided by 1. If the remainder is 0, then the number was converted to an integer, if it is more than 0, then x*1000 failed to convert the number to an int, meaning that it has more than 3 decimals:
const validate = (x, N) => (x * 10**N) % 1 === 0;
console.log(validate(1.5555, 3)); // false
console.log(validate(1.55, 3)); // true
console.log(validate(1.555, 3)); // true
console.log(validate(0.00000001, 3)); // false
You can convert to string using the toString() method, then split at the point . with the .split() method this will result in an array.
The first element in the array is a string containing the whole number part which is not interesting here for us.
The second element at indice 1 in the resulting array is the decimal part as string.
Now you can check the length property of this string if it is equal or less then three which means it has three or less decimal numbers then we return true in the validation function when not we return false.
const x = 1.5555;
const y = 1.555;
const z = 1.55
function validate(num){
return num.toString().split(".")[1].length <= 3;
}
console.log(validate(x));
console.log(validate(y));
console.log(validate(z));
This may solve your problem
let x = 1.5555;
let y = 1.55;
int length = x.Substring(number.IndexOf(".")).Length;
bool result = length > 3 ? true: false;

Using jQuery or JavaScript to find multiples and remainder of 2 numbers

Odd task, but I need to take a given integer, and first divide it by 5, whatever is left, divide by 3, and then show whatever remains.
For instance:
var fives = 19 / 5 = 3 remainder 4
var threes = 4 / 3 = 1 remainder 1
var ones = 1
var fives // 3
var threes // 1
var ones // 1
I can divide and see if it's a multiple, but I'm not sure how to do the conditional statement to pass it through the 2 operations and leave the remainders each time. The integers will always be positive numbers, no decimals.
To get the remainder of a division you have to devide, floor it and multiply it again. That result you have to substrate from your starting number.
Example:
Remainder of 19 / 5: 19 - floor(19 / 5)*5 = 19 - 15 = 4
in javascript code it's:
var remainderOf = (a,b)=>a-Math.floor(a / b)*b;
// calling it:
var result = remainderOf(19, 5); // 4
But the operation sequence: divide, floor, multiply substrate... is known as modulo operation. And you can use it in javascript with the %.sign:
var remainderOf = (a,b)=>a%b;
In your case it should be:
var startingNo = 19;
var remainderOfDevisionBy5 = startingNo % 5;
var remainderOfDevisionBy3 = remainderOfDevisionBy5 % 3;
alert(remainderOfDevisionBy3);
How about this:
var number = 19;
var fives = Math.floor(number / 5);
var threes = Math.floor(number % 5 / 3);
var ones = number % 5 % 3;

Alternative for Math.round()

In JavaScript when value is 4.3, i want it to round off to 4 and if value is 4.5 or above it rounds off to 5. I want all this without using Math.round().
You could also do this:
round=num=>(num-~~num>=0.5?1:0)+~~num;
Explanation:
~~num
is a double bitwise OR, actually it removes everything behind the point so 1.5 => 1
num-~~num
gets the distance to the next lower integer, so e.g. 5.4 => 0.4, 5.6 => 0.6
Some testcases:
http://jsbin.com/gulegoruxi/edit?console
Alternatively, you could transform the number into a string, split it, and round it with the help of a ternary operator.
Example:
// Decimal number
let number = 4.3;
// Convert it into a string
let string = number.toString();
// Split the dot
let array = string.split('.');
// Get both numbers
// The '+' sign transforms the string into a number again
let firstNumber = +array[0]; // 4
let secondNumber = +array[1]; // 3
// Now you can round it checking the second number
let rounded = secondNumber < 5 ? firstNumber : firstNumber + 1; // 4
In one line of code
let rounded = +number.toString().split('.')[1] < 5 ? +number.toString().split('.')[0] : +number.toString().split('.')[0] + 1;
You can do this
function RoundNum(number){
var c = number % 1;
return number-c+(c/1+1.5>>1)*1
}
console.log(RoundNum(2.456));
console.log(RoundNum(102.6));
console.log(RoundNum(203.515));

Javascript Custom rounding approach for decimal

Input number is 21.2791499. I need to round it in 4 decimal places and expected output in is 21.2792, But all the following approaches give 21.2791 as output. What is the best solution to get the desired output.
The number "9" after number "4" should make the number "4" as "5". Then this "5" should make "1" as "2"
Good or bad, my client’s browser is IE6+ only.
Fiddle: https://jsfiddle.net/Lijo/16mgy0xm/1/
var inputNUmber = 21.2791499;
//Approach 1
var a = Math.round(inputNUmber * 10000) / 10000;
document.getElementById("firstText").value= a;
//Approach 2
var b = Number(Math.round(inputNUmber+'e4')+'e-4');
document.getElementById("secondText").value= b;
//Approach 3
var c =inputNUmber.toPrecision(6);
document.getElementById("thirdText").value= c;
So to be clear, you don't want to round to the nearest integer, you want to always round up?
In which case Math.ceil(21.2791499 * 10000) / 10000 = 21.2792
Scale the number up by the required number of decimal places, use the built in ceil function, and then scale it back down.
Alternative solution. It still suffers from floating point math inaccuracy to a point.
Basically it always "rounds" up unless the value has exactly four decimal places.
var inputNUmber = 21.2791499;
//Approach 1
var a = Math.round(inputNUmber * 10000) / 10000;
document.getElementById("firstText").value= a;
//Approach 2
var b = Number(Math.round(inputNUmber+'e4')+'e-4');
document.getElementById("secondText").value= b;
//Approach 3
var c =inputNUmber.toPrecision(6);
document.getElementById("thirdText").value= c;
// Here's my approach
var d = Math.floor(inputNUmber * 10000) / 10000
d += +(d < inputNUmber) / 10000;
document.getElementById("fourthText").value= d;
<input type="text" id="firstText"/>
<br />
<input type="text" id="secondText"/>
<br />
<input type="text" id="thirdText"/>
<br />
<input type="text" id="fourthText"/>
An approach using String.prototype.split() , String.prototype.slice() , Array.prototype.splice() , Array.prototype.join() , Math.round()
var inputNumber = 21.2791499;
// split value at `.` character
var n = String(inputNumber).split(".");
// portion of number after `.` character
var k = n[1];
// convert numbers after `.` to array
var res = k.slice(4).split("");
// add `.` at index `1` of numbers following `.` character
// of original input number; e.g., convert `2791499` to `2791.5`
res.splice(1, 0, ".");
// results
var input = document.getElementById("firstText");
// use `Math.round()` , `.slice()` , `.join()` on resulting number
// following insertion of `.` character
input.value = Math.round( k.slice(0, 4) + "." + Math.round(res.join("")));
<input type="text" id="firstText"/>
jsfiddle https://jsfiddle.net/16mgy0xm/6/
here is a solution to your weird rounding issue https://jsfiddle.net/16mgy0xm/5/
ESSENTIALLY ALL I AM DOING IS ROUNDING THE NUMBER TWICE
see example 1 I am dividing var a after setting var a this sets the value to round at the 5th decimal place, using the second math.round() i am them setting it back to the 4th decimal place to give you your desired effect.
var inputNUmber = 21.2791499;
//Approach 1
var a = Math.round(inputNUmber * 100000) ;
a = a / 100000;
var a1 = Math.round(a * 10000) / 10000;
document.getElementById("firstText").value= a1;

Find out how many thousands and hundreds and tens are there in a amount

I am having a asp application and in that amount column is there. I need to find out how many thousands and hundreds and tens are there in that amount
For example
if i am having amount as 3660 means
1000's - 3
100's - 6
10's - 6
like this i need
Can any body help me
The simple answer is to divide the number by 1000 whatever is the quotient that is the number of 1000's in the amount. Then divide the remainder with the 100's the quotient will be the number of 100's. And then again divide the remainder with 10, the quotient will be the number of 10's
Something like this:
quotient = 3660 / 1000; //This will give you 3
remainder = 3660 % 1000; //This will give you 660
Then,
quotient1 = remainder/ 100; //This will give you 6
remainder1 = remainder % 100; //This will give you 60
And finally
quotient2 = remainder1 / 10; //This will give you 6
Is it not easier to use type coercion and change the data type to string?
Then you can easily check the value by checking the value at selected index position,
var number = 1234;
number2 = new String(number);
var thousands = number2[0];
var hundreds = number2[1];
and so on....
It may not be usable in what you're doing, it was for me :)
If the "javascript" tag is the correct one, then you've already gotten some answers. If the "asp-classic" tag is actually the correct one, then chances are your scripting language is VBScript, not Javascript.
Did you just pick multiples of 10 as an example, or is that the actual multiple you're looking for? Because if it's the latter, then all you need to do is split the number into digits — that's what the base 10 number system means, after all.
Function SplitNum(theNum)
dim L, i, s, n
n = CStr(theNum)
L = Len(n)
s = ""
for i = 1 to 3
if s <> "" then s = "," & s
if i >= L then
s = "0" & s
else
s = Left(Right(n,i+1),1) & s
end if
next
if L > 4 then s = left(n,L-4) & s
SplitNum = s
End Function
If your actual divisors are something other than multiples of 10, you'll need to do arithmetic. The integer division operator in VBScript is \. (Integer division is basically the "opposite" of the modulus function.)
Function GetMultiples(theNum)
dim q, r
q = theNum \ 1000 & ","
r = theNum Mod 1000
q = q & r \ 100 & ","
r = r Mod 100
q = q & r \ 10
GetMultiples = q
End Function
Try this out...
Here is a fiddle that demonstrates how to use the output..
http://jsfiddle.net/Villarrealized/L3AxZ/1/
function getMultiplesOfTen(number){
number = parseInt(number);
if(typeof(number)!=="number") return number;
var result = {};
(function breakDown(num){
if(isNaN(num))return num;//if it's invalid return
if(num<=0)return false;
num = num.toFixed(0);//get rid of decimals
var divisor = Math.pow(10,num.length-1),//ex. when num = 300, divisor = 100
quotient = Math.floor(num/divisor);
result[divisor]=quotient;//add it to our object
breakDown(num % divisor);//break down the remainder
})(number);
//return result as an object
return result;
}
This function will return an object with the multiple of ten as the key and the number as the value
ex. getMultiplesOfTen(150)=={100:1,10:5} == 1 multiple of 100 and 5 multiples of 10.
Let's say we have the number 7354. To find the thousands:
variable a = 7354 / 1000
variable b = a % 10
The number which is stored in variable b now is the number if the thousands.
To find the hundreds:
variable c = 7354 / 100
variable d = a % 10
The number which is stored in variable d now is the number if the hundreds.
To find the tens:
variable e = 7354 / 10
variable f = a % 10
The number which is stored in variable f now is the number if the tens.
To find the ones:
7354 % 10
This works for every number in the place of 7354, even for bigger numbers than 7354.
The first digit in the quotient of 1,592÷64
1
is in the Choose... ones tens hundreds thousands place.
Decide where the first digit of the quotient should be placed. Do not complete the division.
The first digit of the quotient for 2,370÷24
2,370÷24
should be in the Choose... ones tens hundreds thousands place
2021 version here:
Cast your number as a string, spread it and reverse it like so:
x = 1234
x = [...x.toString()].reverse() // [4, 3, 2, 1]
thous = x[3] // 1
hunds = x[2] // 2
tens = x[1] // 3
units = x[0] // 4
y = [...x.toString()].reverse()[3] // 1 because 1000 has 3 zeros
I suppose you can use some fancy system of powers of 10 to get those indexes. So let's do exactly that and get #Villarrealized 15 lines of 2013 code condensed into just a few lines of 2021 code:
function placeValues(someNumber = 1234) {
x = [...someNumber.toString()].reverse().reduce((p, c, i) => {
p[10**i] = c;
return p;
}, {});
return x; // {1000:1, 100:2, 10:3, 1:4}
}

Categories