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).
Related
I need a rounding down many many decimal places down, basically roundTo but supposedly rounding down at the spot. Example,
take the number, 1.087179939485353505
but to the fifth place, with roundTo of 6
roundTo(1.087179939485353505, 6) is 1.08718
I need 1.08717 not 1.08718 in javascript.
var Variable = roundTo(Variable / 1000000000000000000, 6);
Resolved
There seems to be no native javascript decimal rounding function that rounds down. One of two options are available.
Convert to string and manipulate the data that way (makes the most sense).
Utilize a number and multiply, floor then re-divide again for your number
How about convert to string, slice and convert back to number.
const roundTo = num => Number(String(num).slice(0, 7));
console.log(roundTo(1.087179939485353505));
You could use regex to get 5 decimals
function roundTo(number) {
var result= number.toString().match(/^\d+(\.\d{0,5})/)[0];
console.log(result);
}
roundTo(1.087179939485353505);
var Variable = Variable / 1000000000000000000;
Variable *= 1000000;
Variable = Math.floor(Variable);
Variable /= 1000000;
var Variable = roundTo(Variable, 6);
I took my decimal, multiplied it by how many places I wanted to roundTo, math floor for absolute low rounding and divided it once again before lastly using roundTo for the precise decimal place. Seems the only way.
When I pull the values I want to multiply, they're strings. So I pull them, parse them as floats (to preserve the decimal places), and multiply them together.
LineTaxRate = parseFloat(myRate) * parseFloat(myQuantity) * parseFloat(myTaxRateRound);
This has worked for 99% of my invoices but I discovered one very odd problem.
When it multiplied: 78 * 7 * 0.0725
Javascript is returning: 39.584999999999994
When you normally do the math in a calculator its: 39.585
When all is said and done, I take that number and round it using .toFixed(2)
Because Javascript is returning that number, it's not rounding to the desired value of: $39.59
I tried Math.round() the total but I still get the same number.
I have thought of rounding the number to 3 decimals then two, but that seems hacky to me.
I have searched everywhere and all I see is people mention parseFloat loses its precision, and to use .toFixed, however in the example above, that doesn't help.
Here is my test script i made to recreate the issue:
<script>
var num1 = parseFloat("78");
var num2 = parseFloat("7");
var num3 = parseFloat("0.0725");
var myTotal = num1 * num2 * num3;
var result = Math.round(myTotal*100)/100
alert(myTotal);
alert(myTotal.toFixed(2));
alert(result);
</script>
Floating points are represented in binary, not decimal. Some decimal numbers will not be represented precisely. And unfortunately, since Javascript only has one Number class, it's not a very good tool for this job. Other languages have decent decimal libraries designed to avoid precisely this kind of error. You're going to have to either accept one-cent errors, implement a solution server-side, or work very hard to fix this.
edit: ooh! you can do 78 * 7 * 725 and then divide by 10000, or to be even more precise just put the decimal point in the right place. Basically represent the tax rate as something other than a tiny fraction. Less convenient but it'll probably take care of your multiplication errors.
You might find the Accounting.js library useful for this. It has an "improved" toFixed() method.
JavaScript/TypeScript have only one Number class which is not that good. I have the same problem as I am using TypeScript. I solved my problem by using decimal.js-light library.
new Decimal(78).mul(7).mul(0.0725) returns as expected 39.585
hello I want to round an amount in javascript but unable to do and totally stuck.
My scenario is, I have a base amount and marukup % on base. On the basis of these two I want to calculate total amount. I have calculated the amount but i want to round the result.
I have used following formula
amount=base+((base/100)*markup
This formula always give me result without decimal point. I want to get exact amount upto two decimal points. I have used math.round like this
amount=math.round(base+((base/100)*markup).toFixed(2)
but it always return result without decimal point. For example my base value is 121 and markup is 5%. The amount should be 127.05 . But above formula always returns 127. Any guidelines?
I'm pretty sure math.round returns an integer. Even if you round it then, it'll just be 127.00 anyway.
Here's the correct solution(but it isn't easy):
Do not use non-integer values for money!
It doesn't work.
Use an integer in cents.
That is, instead of 127, keep 12700 in your app.
That way all roundings should work fine.
The toFixed(n) function rounds the Number to n decimals, there is no need to use Math.round at all. Try:
total = function (base, markup) { return (base + (base * markup / 100)); };
amount = total(121,5).toFixed(2);
Note that amount will be typeof String and not Number.
This should work:
amout = (Math.round((base*(1+markup))*100)/100).toFixed(2)
By the way, i was using markup as 5/100...
Sound like a integer division problem to me. I'd guess that javascript is seeing the 100 as an int.
Try this:
amount=(base+((base/100.toFixed(2))*markup).toFixed(2)
So I am adding and subtracting floats in javascript, and I need to know how to always take the ceiling of any number that has more than 3 decimal places. For example:
3.19 = 3.19
3.191 = 3.20
3.00000001 = 3.01
num = Math.ceil(num * 100) / 100;
Though, due to the way floats are represented, you may not get a clean number that's to two decimal places. For display purposes, always do num.toFixed(2).
Actually I don't think you want to represent dollar amounts as float, due to the same reason cited by Box9.
For example, 0.1*3 != 0.3 in my browser. It's better to represent them as integers (e.g. cents).
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.