Rounding the result of division in Javascript - javascript

I'm performing the following operation in Javascript:
0.0030 / 0.031
How can I round the result to an arbitrary number of places? What's the maximum number that a var will hold?

Modern browsers should support a method called toFixed(). Here's an example taken from the web:
// Example: toFixed(2) when the number has no decimal places
// It will add trailing zeros
var num = 10;
var result = num.toFixed(2); // result will equal 10.00
// Example: toFixed(3) when the number has decimal places
// It will round to the thousandths place
num = 930.9805;
result = num.toFixed(3); // result will equal 930.981
toPrecision() might also be useful for you, there is another excellent example on that page.
For older browsers, you can achieve it manually using Math.round. Math.round() will round to the nearest integer. In order to achieve decimal precision, you need to manipulate your numbers a bit:
Multiply the original number by 10^x
(10 to the power of x), where x is
the number of decimal places you
want.
Apply Math.round()
Divide by 10^x
So to round 5.11111111 to three decimal places, you would do this:
var result=Math.round(5.111111*1000)/1000 //returns 5.111

The largest positive finite value of the number type is approximately 1.7976931348623157 * 10308. ECMAScript-262 3rd ed. also defines Number.MAX_VALUE which holds that value.

To answer Jag's questions:
Use the toFixed() method. Beware; it returns a string, not a number.
Fifteen, maybe sixteen. If you try to get more, the extra digits will be either zeros or garbage. Try formatting something like 1/3 to see what I mean.

Related

Parsefloat with 2 decimals without losing function to do equations (not as string)

I've seen multiple topics regarding this question, but none seem to answer it.
I want to round a number to two decimals, but without losing the function to use it in equations. So it shouldn't be transformed to a string. This DOES NOT work for what I want: parseFloat("50").toFixed(2)
Does anyone know how to parseFloat with 2 decimals as a number?
Just parse it back to a float.
parseFloat(Number(1.2345).toFixed(2)); //1.23
In javascript a number cannot have trailing zeros. 2.5 is a correct but 2.50 is not, this is why toFixed returns a string, not a number.
The best way to handle what you need is to store the number as a number and let it round out to whatever it needs. Only when showing the number on the screen should you do the toFixed(2) method to transforms it into a string.
// js
const price = 7.999999
const reducedPrice = price * 0.8
const finalReductionPrice = reducedPrice / 2.666666
// html
<p>price {price.toFixed(2)</p>
<p>reducedPrice {reducedPrice.toFixed(2)</p>
<p>finalReductionPrice {finalReductionPrice.toFixed(2)</p>

How to get Power of big number in decimal?

How to get big power of 2 in decimal or
how to convert big exponential value into decimal value.
I want 2 to the power of 128 in decimal not exponential
what I did till now
tofixed(+exponent)
which again given me the same value.
var num = Math.pow(2, 128);
Actual result = 3.402823669209385e+38
expected some decimal value not exponential value.
You could use BigInt, if implemented.
var num = BigInt(2) ** BigInt(128);
console.log(num.toString());
console.log(BigInt(2 ** 128).toString());
3.402823669209385e+38 is a decimal number (in string form, because it's been output as a string). It's in scientific notation, specifically E-notation. It's the number 3.402823669209385 times 100000000000000000000000000000000000000.
If you want a string that isn't in scientific notation, you can use Intl.NumberFormat for that:
console.log(new Intl.NumberFormat().format(Math.pow(2, 128)));
Note: Although that number is well outside the range that JavaScript's number type can represent with precision in general (any integer above Number.MAX_SAFE_INTEGER [9,007,199,254,740,991] may be the result of rounding), it's one of the values that is held precisely, even at that magnitude, because it's a power of 2. But operations on it that would have a true mathematical result that wasn't a power of 2 would almost certainly get rounded.
I think the default power function won't be able to the results you want.
You can refer to the article below to understand how to create an Power function with big number by yourself.
Demo code is not JS but still quite understandable.
↓
Writing power function for large numbers

Converting floating point numbers to integers, rounding to 2 decimals in JavaScript

What's the best way to perform the following conversions in JavaScript? I have currencies stored as floats that I want rounded and converted to integers.
1501.0099999999999909 -> 150101
12.00000000000001 -> 1200
One way to do this is to use the toFixed method off a Number combined with parseFloat.
Eg,
var number = 1501.0099999999999909;
var truncated = parseFloat(number.toFixed(5));
console.log(truncated);
toFixed takes in the number of decimal points it should be truncated to.
To get the output you need, you would only need `toFixed(2)' and multiple the result by 100.
Eg,
var number = 1501.0099999999999909;
var truncated = parseFloat(number.toFixed(2)) * 100;
console.log(truncated);

strip decimal points from variable

I have a series of variables that have a decimal point and a few zeros. How do I strip the variable so it goes from 1.000 to 1?
Simply...
Math.round(quantity);
...assuming you want to round 1.7 to 2. If not, use Math.floor for 1.7 to 1.
use parseInt();
parseInt("1.25");//returns 1
parseInt("1.85");//returns 1
parseInt(1.25);//returns 1
parseInt(1.85);//returns 1
Use number = ~~number
This is the fastest substitute to Math.floor()
parseInt is the slowest method
math.floor is the 2nd slowest method
faster methods not listed here are:
var myInt = 1.85 | 0;
myInt = 1;
var myInt = 1.85 >> 0;
myInt = 1;
Speed tests done here:
http://jsperf.com/math-floor-vs-math-round-vs-parseint/2
Use Math.trunc(). It does exactly what you ask. It strips the decimal.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc
For rounding numbers to the nearest Integer you can use Math.round() like so:
Math.round("1.000"); // Will produce 1
Math.round(123.4234); // Will produce 123
You don't need jQuery for this.
You can use parseInt just fine. From the page:
document.write(parseInt("10.33") + "<br />"); // 10
Here's another nice example:
I often use Math.round and toLocateString to convert numbers containing decimal places, into a more readable string, with thousand separators:
var myNumberAsString = "1234567.890123" // "1234567.890123"
var myNumber = Math.round(0.0 + myNumberAsString); // 1234568
return myNumber.toLocaleString(); // "1,234,568"
I find this useful when loading decimal values from, say a JSON Web Service, and need to display them in a friendlier format on a web page (when, of course, I don't need to display all of the decimal places).
A faster, more efficient way would be to use JavaScript's bitwise operators, like so:
function stripDecimals(n) {
return n | 0;
}
// examples:
stripDecimals(23.245); // => 23
stripDecimals(100.015020); // => 100
The | (OR operator) will treat the numbers as 32-bit (binary 0s and 1s), followed by returning the desired result depending on the operands, which in this case would result to an integer stripped of all decimal places.
I suggest you use something called Math.trunc()... put your number in the parentheses. The reason I don't suggest you use Math.round() is that it might change the integer part of your decimal number which some people won't want though you can use Math.round() if you know you want to get the closest integer.

JavaScript rounding numbers

I know that I can round a number like this
var number = 1.3;
Math.round(number);
and the result I'm given is 1.
But how can I round a number to the next highest whole number? So round 1.3 to 2 instead of 1?
Use Math.ceil() instead. It rounds the number up.
var rounded = Math.ceil(number);
As an aside, in platforms with no ceil method available, and assuming round rounds to the nearest integer, a common trick used to round upwards is:
var rounded = Math.round(number + 0.5);
Don't forget Math.floor(number)!
Although, I would recommend against using javascript to do arithmetic... I don't know the exact reasons (but i just asked a question =P).

Categories