Javascript output showing Nan when i enter large values like 6564646464,6516654,555 input values?
$("#calculate").click(function () {
var need_hotel = $("#hotel_need").val();
var event_day = $("#event_day").val();
var result_1 = parseFloat(need_hotel * event_day);
var result_2 = result_1 * 165;
var result_3 = result_2 * 0.03;
$("#ans1").text(result_1.toFixed(2));
$("#ans2").text(result_2.toFixed(2));
$("#ans3").text('£' + (result_3).toLocaleString('en'));
$("#results_container").show();
});
Javascript has iffy support for such large numbers
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER
You might wanna try BigInt
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt
Related
I have a script, where I can convert gigs to megs to kilobytes to bytes to bits.
After that it uses the .toExponential function to turn it into scientific notation.
But I want it to change into an exponent, instead of it being +e# I want it to be ^#, any way I can change it to print that way instead, if not, anyway I can alter the string to change +e to ^?
Code:
console.log('calculator');
const gigabytes = 192;
console.log(`gigabytes equals ${gigabytes}`);
var megabytes = gigabytes * 1000;
console.log(`megabytes = ${megabytes}`);
var kilabytes = megabytes * 1000;
console.log (`kilabytes = ${kilabytes}`);
bytes = kilabytes * 1000;
console.log(`bytes = ${bytes}`);
bites = bytes * 8;
console.log(`bites are equal to ${bites}`);
console.log (bites.toExponential());
You can use .replace:
const bytes = '1.536e+12'
console.log(convert(bytes))
const inputs = [
'1.536e+12',
'1.536e-12',
'123',
'-123',
'123.456',
'-123.456',
'1e+1',
'1e-1',
'0e+0',
'1e+0',
'-1e+0'
]
function convert(value) {
return value.replace(/e\+?/, ' x 10^')
}
inputs.forEach(i => console.log(convert(i)))
You can just replace e+ with ^ using replace
console.log('calculator');
const gigabytes = 192;
console.log(`gigabytes equals ${gigabytes}`);
var megabytes = gigabytes * 1000;
console.log(`megabytes = ${megabytes}`);
var kilabytes = megabytes * 1000;
console.log (`kilabytes = ${kilabytes}`);
bytes = kilabytes * 1000;
console.log(`bytes = ${bytes}`);
bites = bytes * 8;
console.log(`bites are equal to ${bites}`);
console.log (bites.toExponential().replace(/e\+/g, '^'));
Instead of using
console.log(bites.toExponential);
You may need to use
bites = bites.toExponential;
console.log(bites.replace(“e+”, “*10^”);
Hope this helped!
This question already has answers here:
Javascript concatenating numbers, not adding up
(3 answers)
Closed 5 years ago.
I am using these in my code:
alert(mult); //1.114
alert(profit); //10
price = (mult * profit) + profit;
alert(price); //11.14 should be 21.14
I also tried price = ((mult*profit) + profit); but got the same result. Instead of doing (1.114*10) + 10; it is doing 1.114*10=11.14. It is not adding the additional 10 at the end.
It works fine for me like this. It doesn't seem that concatenation is an issue, because otherwise the value would be '11.1410'.
var mult = 1.114;
var profit = 10;
var price = (mult*profit) + profit;
alert(price);//11.14 should be 21.14
If the profit variable (or both variables) is a string, the result would be "11.1410".
var mult = 1.114;
var profit = '10';
var price = (mult*profit) + profit;
alert(price);//11.1410
The result seems unaffected if just the mult value is a string.
var mult = '1.114';
var profit = 10;
var price = (mult*profit) + profit;
alert(price);//21.14
The variables are probably strings, use parseFloat to convert them to numbers :
mult = parseFloat(mult);
profit = parseFloat(profit);
price = (mult*profit) + profit
The problem is probably that either mult or profit are of type string and not of type number. This can be fixed by explicitly casting.
You can determine the type of your variables in your browser console (i.e. dev tools) with the typeof keyword like this:
typeof foo
If either of your variables are of type string you can convert them to number with parseFloat:
mult = parseFloat(mult);
I just ran this is in the chrome js console F12 key.
var mult = 1.114, profit = 10;
console.log('mult=', mult);//1.114
console.log('profit=', profit);//10
price = (mult*profit) + profit;
console.log('price=', price);//11.14 should be 21.14
And got these results
mult= 1.114
profit= 10
price= 21.14
Was using ExtJS for formatting numbers to percentage earlier. Now as we are not using ExtJS anymore same has to be accomplished using normal JavaScript.
Need a method that will take number and format (usually in %) and convert that number to that format.
0 -> 0.00% = 0.00%
25 -> 0.00% = 25.00%
50 -> 0.00% = 50.00%
150 -> 0.00% = 150.00%
You can use Number.toLocaleString():
var num=25;
var s = Number(num/100).toLocaleString(undefined,{style: 'percent', minimumFractionDigits:2});
console.log(s);
No '%' sign needed, output is:
25.00%
See documentation for toLocaleString() for more options for the format object parameter.
Here is what you need.
var x=150;
console.log(parseFloat(x).toFixed(2)+"%");
x=0;
console.log(parseFloat(x).toFixed(2)+"%");
x=10
console.log(parseFloat(x).toFixed(2)+"%");
Modern JS:
For any of these, remove * 100 if you start with a whole number instead of decimal.
Basic
const displayPercent = (percent) => `${(percent * 100).toFixed(2)}%`;
Dynamic with safe handling for undefined values
const displayPercent = (percent, fallback, digits = 2) =>
(percent === null || percent === undefined) ? fallback : `${(percent * 100).toFixed(digits)}%`;
Typescript:
const displayPercent = (percent: number) => `${(percent * 100).toFixed(2)}%`;
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
function myFunction(num) {
number = num.toString();;
console.log(number)
var words2 = number.split(".");
for (var i = 0; i < words2.length; i++) {
words2[i] += " ";
}
num1 = words2[0];
num2 = words2[1];
num1 = num1.trim();
if(num2==undefined){
number1 = num1+'.00%';
return number1;
}else{
num2 = num2.trim();
number1 = num1+'.'+num2+'%';
return number1;
}
}
document.getElementById("demo").innerHTML = myFunction(50.12);
</script>
</body>
</html>
I had decimal values such as 0.01235 and 0.016858542 that I wanted to convert to percentages 1.235% and 1.6858542% respectively. I thought it was going to be easy, just calculate (0.012858542 * 100) and I'm good to go. I was wrong, (0.012858542 * 100) = 1.2858542000000002 because of decimal conversion.
Let's add toFixed() to the calculation and I end up with the right value.
(0.012858542*100).toFixed(7) // returns "1.2858542"
(0.01235*100).toFixed(7) // returns "1.2350000"
I don't like to show four trailing zeros when they're unnecessary. One solution I thought about was to use replace() to remove all trailing zeros but I ended up using Numeral.js instead because it does all the work for me while it's lightweight. I can recommend it!
import numeral from 'numeral';
numeral(0.012858542 * 100).format('0.00[0000]') // returns "1.2858542"
numeral(0.01235 * 100).format('0.00[0000]') // returns "1.235"
Transform number to percentage with X float decimal positions
function toPercent(number, float) {
var percent = parseFloat(number * 100).toFixed(float) + "%";
return percent;
}
I have this JavaScript function (see below). It only return whole number, it only works when I inputted a whole number. But when I inputted decimal value it doesn't work.
What should I do to handle decimal value?
function calc()
{
var license=parseInt(document.getElementById("license").value);
var service=parseInt(document.getElementById("service").value);
var amount=parseInt(license)+parseInt(service);
var mult=service*(parseInt(document.getElementById("preterms").value) / 100);
var mult1=service*(parseInt(document.getElementById("blueterms").value) / 100);
var mult2=service*(parseInt(document.getElementById("configterms").value) / 100);
document.getElementById("amount").value = amount;
document.getElementById("pre").value = mult;
document.getElementById("blue").value = mult1;
document.getElementById("config").value = mult2;
}
Thanks in advance.
change parseInt to parseFloat, like
var license=parseInt(document.getElementById("license").value);
to
var license=parseFloat(document.getElementById("license").value);
Since you are working with decimal values You need to use parseFloat instead of parseInt
ex:
function calc() {
var license = parseFloat(document.getElementById("license").value);
var service = parseFloat(document.getElementById("service").value);
var amount = parseFloat(license) + parseFloat(service);
var mult = service * (parseFloat(document.getElementById("preterms").value) / 100);
var mult1 = service * (parseFloat(document.getElementById("blueterms").value) / 100);
var mult2 = service * (parseFloat(document.getElementById("configterms").value) / 100);
document.getElementById("amount").value = amount;
document.getElementById("pre").value = mult;
document.getElementById("blue").value = mult1;
document.getElementById("config").value = mult2;
}
It looks like folks suggested using parseFloat. The next issue you're likely to run into is formatting the output. You can use toFixed to output your percentages with a fixed number of decimals:
(12.34567).toFixed(2)
// => "12.35"
I have a simple form, with 5 textboxes and 3 answers (also textboxes). The form calculates a result for the user with number inputs. My problem is my calculation does not work in IE, but works fine in both Chrome and Firefox.
What's wrong?
Here is my function:
function addNumbers()
{
var val1 = Number(document.getElementById("value1").value);
var val2 = Number(document.getElementById("value2").value);
var val3 = Number(document.getElementById("value3").value);
var val4 = Number(document.getElementById("value4").value);
var val5 = Number(document.getElementById("value5").value);
var val6 = '100';
var ansD1 = document.getElementById("answer1");
ansD1.value = Number((val1 * val2) * (val4 / val6));
var ansD2 = document.getElementById("answer2");
ansD2.value = Number((val1 * val3) * (val5 / val6));
var ansD3 = document.getElementById("answer3");
ansD3.value = Number (ansD1.value - ansD2.value);
}
Change this line:
var val6 = '100';
to this:
var val6 = 100;
You want all your values to be actual numbers (not strings) so you can do math on them.
Also, you don't need the Number() in these lines because the result of the numeric math is already a number. Plus the assignment to the answer fields is just going to convert the result to a string anyway:
ansD1.value = Number((val1 * val2)*(val4/val6));
They can just be this:
ansD1.value = (val1 * val2)*(val4/val6);
The modified code works fine in IE here: http://jsfiddle.net/jfriend00/5WFRA/.
Instead of Number use parseInt, otherwise they are treated as strings