Javascript Number Formatting - javascript

Certainly a stupid question, please forgive me. My customer wants decimal numbers to display with five digits. For example: 100.34 or 37.459. I was accomplishing this with val.toPrecision (5);; however, when my numbers get really small, I stop getting what I want. For example, if my number is 0.000347, it displays 0.00034700. Now, I understand why it's doing this, but what I don't know is how to get it to display 0.0003. Any thoughts?

Math.round(0.000347 * 1e4) / 1e4
Or with toFixed:
Number.prototype.toNDigits = function (n) {
return (Math.abs(this) < 1) ?
this.toFixed(n - 1) :
this.toPrecision(n);
};
http://jsfiddle.net/HeQtH/6/

Our problem is with numbers less than 1 obviously. So catch them and deal them separately
function SetPrecisionToFive(n){
return (n > 1) ? n.toPrecision (5) : (Math.round(n * 1e4) / 1e4).toString();
}

You can use the toFixed method to accomplish this. For example: (0.000347).toFixed(4)

The Javascript toFixed() function will truncate small numbers to a fixed decimal precision, eg:
var num = .0000350;
var result = num.toFixed(5); // result will equal .00003

Related

When the result is round (1.10 1.30) does not display the 2nd decimal How do I do it?

My program (which uses Math.round) does not display the second decimal when the result is round (ex: 1.10, 1.30) while yes when the result is not round (ex: 1.24, 2.47). How to change this?
function calcAmount2() {
var userAmount2 = document.getElementById("amount2").value;
if (userAmount2 = Number(amount2.value)) {
document.getElementById("marginAmount2").textContent =
Math.round(userAmount2 * 3) / 100 + "€";
}
}
(expected)1.10, 1.30 instead of (actually) 1.1 1.3
(Math.round(userAmount2 * 3) / 100).toFixed(2) + "€";
toFixed sets the number to always have 2 decimals.
I believe this is a duplicate of Format number to always show 2 decimal places
You want to use .toFixed(2) it seems, though be aware the result will be a String.
I am not sure how specific your answer has to be, but I would recommend you to use this instead:
const res = Number(Math.round(userAmount2 +'e2')+'e-2');
This is because toFixed has the rounding problem for some values such as 21.005.
Let me prove it to you over here:
console.log(Number(Math.round(20.005 +'e2')+'e-2'));
console.log(20.005.toFixed(2));

How to remove trailing decimals without rounding up?

For example, I have a number 123.429. How can I remove the trailing decimals without rounding up to two decimal place.
Hence, I need the number to be up to two d.p. i.e 123.42.
Definitely toFixed() method or Math.round(num * 100) / 100 cannot be used in this situation.
The function you want is Math.floor(x) to remove decimals without rounding up (so floor(4.9) = 4).
var number = Math.floor(num * 100) / 100;
Edit: I want to update my answer because actually, this rounds down with negative numbers:
var Math.floor(-1.456 * 100) / 100;
-1.46
However, since Javascript 6, they have introduced the Math.trunc() function which truncates to an int without rounding, as expected. You can use it the same way as my proposed usage of Math.floor():
var number = Math.trunc(num * 100) / 100;
Alternatively, the parseInt() method proposed by awe works as well, although requires a string allocation.
var number = parseInt('' + (num * 100)) / 100;
You can convert it to a string and then simply truncate the string two places after the decimal, e.g.:
var s = String(123.429);
s.substring(0, s.indexOf('.') + 3); // "123.42"
Please note that there's no guarantee if you convert that final string back into a number that it'll be exactly representable to those two decimal places - computer floating point math doesn't work that way.
another v. cool solution is by using | operator
let num = 123.429 | 0
let num = 123.429 | 0
console.log(num);
let's get the variable name as "num"
var num = 123.429;
num=num*100;
num=num.toString();
num=num.split(".");
num=parseInt(num[0]);
num=num/100;
value of the num variable will be 12.42
Try this
number = parseFloat(number).toFixed(12);
number = number.substring(0, number.indexOf('.') + 3);
return parseFloat(number);
Not the fastest solution but the only one that handles an edge case like 0.0006*10000 = 5.999999999 properly, i.e. if you want to truncate to 4 decimal places and the value is exactly 0.0006, then using Math.trunc(0.0006 * (10 ** 4))/(10 ** 4) gives you 0.0005.

JavaScript factorial prevent infinity

I have been using this function for calculating factorial numbers in JavaScript:
var f = [];
function factorial (n) {
if (n == 0 || n == 1)
return 1;
if (f[n] > 0)
return f[n];
return f[n] = factorial(n-1) * n;
}
All seemed to be going well until I tried the number 500. It returned infinity.
Is there a way that I can prevent infinity as an answer?
Thank you.
You indeed need to use bignumbers. With math.js you can do:
// configure math.js to work with enough precision to do our calculation
math.config({precision: 2000});
// evaluate the factorial using a bignumber value
var value = math.bignumber(500);
var result = math.factorial(value);
// output the results
console.log(math.format(result, {notation: 'fixed'}));
This will output:
1220136825991110068701238785423046926253574342803192842192413588385845373153881997605496447502203281863013616477148203584163378722078177200480785205159329285477907571939330603772960859086270429174547882424912726344305670173270769461062802310452644218878789465754777149863494367781037644274033827365397471386477878495438489595537537990423241061271326984327745715546309977202781014561081188373709531016356324432987029563896628911658974769572087926928871281780070265174507768410719624390394322536422605234945850129918571501248706961568141625359056693423813008856249246891564126775654481886506593847951775360894005745238940335798476363944905313062323749066445048824665075946735862074637925184200459369692981022263971952597190945217823331756934581508552332820762820023402626907898342451712006207714640979456116127629145951237229913340169552363850942885592018727433795173014586357570828355780158735432768888680120399882384702151467605445407663535984174430480128938313896881639487469658817504506926365338175055478128640000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
500! is, for lack of a better term, "[bleep]ing huge".
It is far, far beyond what can be stored in a double-precision float, which is what JavaScript uses for numbers.
There's no way to prevent this, other than use numbers that are reasonable :p
EDIT: To show you just how huge it is, here's the answer:
500! = 1220136825991110068701238785423046926253574342803192842192413588385845373153881997605496447502203281863013616477148203584163378722078177200480785205159329285477907571939330603772960859086270429174547882424912726344305670173270769461062802310452644218878789465754777149863494367781037644274033827365397471386477878495438489595537537990423241061271326984327745715546309977202781014561081188373709531016356324432987029563896628911658974769572087926928871281780070265174507768410719624390394322536422605234945850129918571501248706961568141625359056693423813008856249246891564126775654481886506593847951775360894005745238940335798476363944905313062323749066445048824665075946735862074637925184200459369692981022263971952597190945217823331756934581508552332820762820023402626907898342451712006207714640979456116127629145951237229913340169552363850942885592018727433795173014586357570828355780158735432768888680120399882384702151467605445407663535984174430480128938313896881639487469658817504506926365338175055478128640000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
That right there is a 1,135-digit number. For comparison, double-precision floats can handle about 15 digits of precision.
You could consider using an arbitrary precision numeric library. This is a question of its own, though. Here's one related question: https://stackoverflow.com/questions/744099/is-there-a-good-javascript-bigdecimal-library.
I dont know if anyone has solved this elsewise...
I'm a novice beginner in coding and dont know all the aspects. But after I faced this factorial problem myself, i came here when searching for the answer. I solved the 'infinity' display problem in another way. I dont know if its very efficient or not. But it does show the results of even verry high intergers.
Sorry for any redundancy or untidiness in the code.
<!DOCTYPE html>
<html>
<head>
<title>Factorial</title>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'></script>
</head>
<body>
<input type='text' id='number' />
<input type='button' value='!Factorial!' id='btn' />
<script>
var reslt=1;
var counter=0;
var mantissa=0; //stores the seperated matissa
var exponent=0; //stores the seperated exponent
$(document).ready(function (){
$('#btn').click(function (){
var num=parseFloat($('#number').val()); //number input by user
for(i=1;i<=num;i++){
reslt=reslt*i;
//when the result becomes so high that the exponent reaches 306, the number is divided by 1e300
if((parseFloat(reslt.toExponential().toString().split("e")[1]))>=300){
reslt=reslt/1e300; //the result becomes small again to be able to be iterated without becoming infinity
counter+=1; //the number of times that the number is divided in such manner is recorded by counter
}
}
//the mantissa of the final result is seperated first
mantissa=parseFloat(reslt.toExponential().toString().split("e")[0]);
//the exponent of the final result is obtained by adding the remaining exponent with the previously dropped exponents (1e300)
exponent=parseFloat(reslt.toExponential().toString().split("e")[1])+300*counter;
alert(mantissa+"e+"+exponent); //displays the result as a string by concatenating
//resets the variables and fields for the next input if any
$('#number').val('');
reslt=1;
mantissa=0;
exponent=0;
counter=0;
});
});
</script>
</body>
</html>
Javascript numbers can only get so big before they just become "Infinity". If you want to support bigger numbers, you'll have to use BigInt.
Examples:
// Without BigInt
console.log(100 ** 1000) // Infinity
// With BigInt
// (stackOverflow doesn't seem to print the result,
// unless I turn it into a string first)
console.log(String(100n ** 1000n)) // A really big number
So, for your specific bit of code, all you need to do is turn your numeric literals into BigInt literals, like this:
var f = [];
function factorial (n) {
if (n == 0n || n == 1n)
return 1n;
if (f[n] > 0n)
return f[n];
return f[n] = factorial(n-1n) * n;
}
console.log(String(factorial(500n)));
You'll find that you computer can run that piece of code in a snap.
Hi this is due to the nature of java script as it can't represents number above 253-1 reference so to solve this either wrap the number with BigInt(n) or add to the number >> 3n
const factorial = (n) => {
n = BigInt(n)
if ( n < 1 ) return 1n
return factorial(n - 1n) * n
}

JQuery round up the length of a result

I am using this code:
$("#total_percentage").text(
(parseInt($("#capacity").text(), 10) / parseInt($("#total").text(), 10))
);
My problem is that #total_percentage sometimes gives a long result.
e.g: 2.33333333333
Is there a way to setting it so it rounds up / shows only max of 2 digits?
for example: 2 or 10
To round up use the Javascript Math library.
$("#total_percentage").text(
(Math.ceil(parseInt($("#capacity").text(), 10) / parseInt($("#total").text(), 10)))
);
You can use toFixed():
$("#total_percentage").text(
(parseInt($("#capacity").text(), 10) / parseInt($("#total").text(), 10)).toFixed(2)
);
References:
toFixed().
If you want to display two digits to the right of the decimal, Math.toFixed is the solution:
(2.33333333).toFixed(2) === "2.33"
Note that this results in a string, not a number. If you want to display 2 digits total, Math.toPrecision is what you want:
(2.33333333).toPrecision(2) === "2.3"
Again, this results in a string. To get back to a number (if desired), you can use parseFloat.
A final note that both these functions will also round your number. For example:
(1.23456).toPrecision(4) === "1.235"
If you want to truncate your number without rounding, you can write a function like this:
function truncate(num,precision) {
var muldiv = Math.pow(10,precision-1);
return Math.floor(num * muldiv) / muldiv;
}
truncate(1.23456,4) === 1.234
Here is a jsFiddle demonstrating each method:
---jsFiddle DEMO---

Getting a sum without rounding it off to two decimal places

Forgive me if I'm too noob about this. Recently, I post a question regarding the rounding off two decimal places. Now, How can I get the sum of these numbers but I only need the two decimals w/out rounding it off. This is javascript im working.
Example: 12.876 + 36.278 = 49.154. I need this answer to be... 49.15 only. Or
another one: 12.876 + 1 = 13.876. I need this answer to be... 13.87
Here is my code (with round off to two decimal places)
function civ(){
civ1=Number(document.addition.scc.value);
civ2=Number(document.addition.ccc.value);
civ3=Number(document.addition.ncc.value);
civ4=Number(document.addition.vch.value);
civ5=Number(document.addition.mch.value);
civ6=Number(document.addition.nlch.value);
civ7=Number(document.addition.slch.value);
valNum1=Math.round((civ1+civ2+civ3+civ4+civ5+civ6+civ7)*10)/10;
document.addition.civ123.value=valNum1;
}
Super thanks to those who are helping me everyday! :)
Math.floor(N * 100) / 100
Will strip off past two decimal places; Math.floor() is essentially Round Down no matter what.
Math.floor(N * 100) / 100 may not work always.
For Example,
4.56 becomes 4.55
If myNumber is the number you want to have two decimals...
myNumber.toFixed(2)
should work. Source: http://www.w3schools.com/jsref/jsref_tofixed.asp
A very old question, but I saw it didn't have an acceptable answer. As #user3006769 mentioned, some numbers don't work if you use Math.floor(N*100)/100.
Another approach is to count how many digits there are before the decimal, then convert your number to a string, chop off any characters to the right of the 2nd decimal, then convert it back to a number:
function roundDownDecimals(num, decimals) {
const preDecimalDigits = Math.floor(num).toFixed(0).length;
return parseFloat(num.toFixed(decimals + 1).slice(0, preDecimalDigits + decimals + 1));
}
roundDownDecimals(4.56, 2);
// returns 4.56
roundDownDecimals(13.876, 2);
// returns 13.87
roundDownDecimals(4.10, 2);
// returns 4.1
If you need to preserve trailing 0's, leave off the parseFloat.
function roundDownDecimals(num, decimals) {
const preDecimalDigits = Math.floor(num).toFixed(0).length;
return num.toFixed(decimals + 1).slice(0, preDecimalDigits + decimals + 1);
}
roundDownDecimals(4.10, 2);
// returns "4.10"

Categories