This question already has answers here:
How do I check that a number is float or integer?
(52 answers)
Closed 7 years ago.
im trying to check if a number is a whole after a calculation. What I have so far prints out how many times one number gets divided by another, but when the number is not whole it dose not print anything out. Heres my code:
function round() {
var percent = document.getElementById('percent_sale').value;
var perShare = document.getElementById('singleShare').value;
var result = (percent / perShare);
if(result % 1 == 0) {
document.getElementById('results1').innerHTML = ('Number of shares:'+result);
} else {
document.getElementById(results1).innerHTML = ('number of shares must ');
}
}
The values get input buy a user, and the percent for sale is say 50 and the single share is say 2.5 this would return 20 shares.
What I need is if I put in something like 50 for sale and 3.15 single share it tells the user to make equal number of shares as it would return 15.87
Any ideas where ive gone wrong?
Convert your number into string and then check if the string contains only numbers
var num = 15;
var n = num.toString();
This will convert it into string then this
String.prototype.isNumber = function(){return /^\d+$/.test(this);}
console.log("123123".isNumber()); // outputs true
console.log("+12".isNumber()); // outputs false
For further reference.Link StackOverFlow
Related
This question already has answers here:
How can I remove the decimal part from JavaScript number?
(16 answers)
Closed 2 months ago.
How can i make the result of the calculation to display no decimals - for all the results ?
now the number is variable on a slider that gives a number from : 5000 - 100000
and is then divided or multiplied with : X
the problem if X is somthing like : * 0.0001097 the number i is a mile long
i just want the result to be wihtout decimals
i am a real amateur in this field.. have mercy with me hahah
function do_on_range_change_pages() {
$('.betrag').text(pages);
$('.name1').text((pages * 0.001));
$('.name2').text((pages * 0.03));
$('.name3').text((pages / 22));
}
*how can i make the result of this display no decimals ?*
$('.name3').text((pages / 22 **?????**));
In Javascript, you could remove decimals with severals solutions !
The parseInt() function is the slower (!).
let myNumber = 5.0214;
let myOtherNumber = 5.9;
// With Math.floor() method
let myNymberWithoutDecimals = Math.floor(myNumber) // 5
let myOtherWithoutDecimals = Math.floor(myOtherNumber) // 5
// With Math.round() method
let myNymberWithoutDecimals = Math.round(myNumber) // 5
let myOtherWithoutDecimals = Math.round(myOtherNumber) // 6
// with parseInt()
let myNymberWithoutDecimals = parseInt(myNumber) // 5
let myOtherWithoutDecimals = parseInt(myOtherNumber) // 5
// with toFixed(number)
myNumber.toFixed(2) // 5.02
myNumber.toFixed(1) // 5.0
myNumber.toFixed() // 5
With your example :
function do_on_range_change_pages() {
$('.betrag').text(pages);
$('.name1').text((pages * 0.001).toFixed());
$('.name2').text((pages * 0.03).toFixed());
$('.name3').text((pages / 22).toFixed());
}
Better advice : new to JS ? Try to use google.
My research : https://www.jsdiaries.com/how-to-remove-decimal-places-in-javascript/
Try https://beta.sayhello.so/, this search engine could find snippets :) !
Have a nice day :)
This question already has answers here:
How to decide between two numbers randomly using javascript?
(4 answers)
Closed 1 year ago.
I've searched a lot for generating a random number but all I got is generating for a range between a or b.
I'm trying to get a number from a or b, i.e. either a or b, none from in between.
This returns the first value only
var number = 1 || 9; \\9
You can store your two numbers in an array and get a random index of that array. Here's an example:
var yourTwoNumbers = [2,5]
console.log(yourTwoNumbers[Math.floor(Math.random() * yourTwoNumbers.length)]);
So Math.random() randomly generates a number between 0.0 and 1.0. Math.random() < 0.5 has a 50% percent chance of either being true or false. This way you can select one of two numbers with equal probability.
let number = Math.random() < 0.5 ? 1 : 9;
console.log(number)
The same asked here: How to decide between two numbers randomly using javascript?
There is already an answer with explanations.
The Math.random[MDN] function chooses a random value in the interval [0, 1). You can take advantage of this to choose a value randomly.
const value1 = 1
const value2 = 9;
const chosenValue = Math.random() < 0.5 ? value1 : value2;
console.log(chosenValue)
This question already has answers here:
How to convert a string to an integer in JavaScript
(32 answers)
Why is one string greater than the other when comparing strings in JavaScript?
(5 answers)
Closed 1 year ago.
I have this javascript code that is working mostly as intended. It is two functions, the first prompts the user for two values on a button press, and the second compares them and displays an output on another button press.
It works almost perfectly, except the outputs don't make sense. It is supposed to output 'true' if inpOne is greater than inpTwo, and 'false' otherwise.
If both inputted numbers are less than 10 i.e. inpOne = 8, inpTwo = 1, it will output true, as it should. However, if inpOne = 20, and inpTwo = 3, it outputs 'false' which is incorrect. I've tried with many other values and it seems to be random to some extent... Can someone look over my code and tell me what I'm doing wrong? Thanks!
Edit: I realize it is three functions, the last function just displays the results to an HTML element...
let inpOne;
let inpTwo;
function promptForCompare() {
inpOne = prompt('Enter first number','');
inpTwo = prompt('Enter second number','');
}
function checkIfGreater() {
let valComp = inpOne > inpTwo ? true : false;
return displayResult(valComp), console.log(valComp);
}
function displayResult(input) {
if (input == true) {
document.getElementById("resDisp").innerHTML = "Number is greater!";
} else {
document.getElementById("resDisp").innerHTML = "Number is NOT greater!";
}
}
This question already has answers here:
Adding two numbers concatenates them instead of calculating the sum
(24 answers)
Closed 1 year ago.
Does anyone know why the exponent and round up functions aren't giving me the correct answers? I've gone through a load of debugging and I can't figure out what I'm doing that's making it's value abnormally large (like 25 orders larger)
function CAPEX(){
var initial = document.getElementById("CAPEX").value;
var lifespan = document.getElementById("life").value;
var interest = document.getElementById("IR").value;
var capitalrepayment = initial/lifespan;
var i;
var cap=0;
var expense =0;
for (i=0; i<lifespan;i++){
expense = capitalrepayment + (initial*interest);
cap = cap + expense;
initial = initial - capitalrepayment;
}
denominator = Math.pow((1+interest), lifespan);
console.log(denominator);
return cap;
}
I have a similar sort of issue here too where Math.ceil is returning a completely different answer too.
if(selected_scenario == "Divers"){
var totalTechnicians = numberNeeded * 3;
var supervisors = totalTechnicians/3;
var othertechnicians = totalTechnicians-supervisors;
var boats= Math.ceil((totalTechnicians+numberNeeded)/12);
divertotal = (numberNeeded*580)+(supervisors*516)+(othertechnicians*276)+(boats*2345)+9230+(boats*20);
}
For reference interest is 0.02, lifespan is 25, numberNeeded is 23. I'm reading these values in directly from a form number input.
The denominator should be 1.64 and boats should be 8.
The values that you are getting from the DOM are strings. You need to convert them to numbers before you can apply any mathematical operations to them. Try using parseInt() or parseFloat()
This question already has an answer here:
Format a javascript number with a Metric Prefix like 1.5K, 1M, 1G, etc [duplicate]
(1 answer)
Closed 7 years ago.
To start with you need...
function m(n,d){x=(''+n).length,p=Math.pow,d=p(10,d)
x-=x%3
return Math.round(n*d/p(10,x))/d+" kMGTPE"[x/3]}
Then calling like so...
// m( ANY NUMBER HERE or VAR LIKE I USE,HOW DECIMAL PLACES)
m(110000,2)
However instead of the above's result of 0.11M, I would like it to display 110k.
What you have there is an example of an overly optimized script, lets make it more developer friendly an readable
function metricPrefix(rawNumber,decimalPlaces){
var sufixes= " kMFGPE";
var numberLength =(''+n).length;
decimalPlaces=Math.pow(10,d); //raise 10 to the number of decimal places
var modLen = numberLength - numberLength%3;
var sufix = sufixes[modLen/3];
return Math.round(rawNumber*decimalPlaces/decimalPlaces(10,modLen))/decimalPlaces+ sufix;
}
Now it's easier to work with. We can see the issue is that we need to adjust for when the string is divisible by 3, so lets fix that.
function metricPrefix(rawNumber,decimalPlaces){
var sufixes= " kMFGPE";
var numberLength =(''+rawNumber).length;
decimalPlaces=Math.pow(10,decimalPlaces); //raise 10 to the number of decimal places
//THis is the change
//If the length is divisable by 3 take 3 off the length
var modLen = numberLength%3 == 0 ? numberLength - 3 - (numberLength%3) : numberLength - (numberLength%3);
console.log(modLen);
var sufix = sufixes[(modLen/3)]
console.log(sufix)
return Math.round(rawNumber*decimalPlaces/Math.pow(10,modLen))/decimalPlaces+ sufix;
}
$(document).ready(function(){
$("#result").html(metricPrefix(110000,2));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="result"></div>