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>
I have this problem with rounding up or rounding off with javascript. Well it gets the job done but there are some scenarios that it fails to do the job properly.
For example.
The price is 0.30 with a 15% discount should have 0.255 or 0.26 as result. (this is somehow okay)
The price is 79.99 with a 50% discount should have 40 as result. (actual result is 39.995)
Tried using this as reference Using toFixed(2) and math round to get correct rounding
also did this process Math.round(value*Math.pow(10,dec))/Math.pow(10,dec);
Any ideas?
Thanks
This is my initial test. Though this is just an initial test what I did is checked if the last two digits is greater than 5 then apply Math.ceil that would to the 0.255 to be 0.26 but when using 39.99 the result would still be 39.99 though 39.99 should use Math.round so that the result would be 40.
What I would like to accomplish is to be able to round up or round down any number if it needs rounding up or if it needs rounding up.
UPDATE
I was able to solve my own problem. (Atleast to my specific environment)
http://jsfiddle.net/xMj3M/4/
This is because of how floats are handled. I would suggest having your original numbers in integers only, so you would start with 7999. If you use this method, you will get the correct result.
In general, especially when dealing with money, it is always a good idea to work in pennies first, and then output it in the format of the currency.
You could try:
var someNumber = 36.7327;
var someNumberRoundedTo2Decimals = (Math.round((someNumber * 100)) / 100);
// = 36.73
basically this moves the decimal to the right 2 digits..
3673.27
then rounds it off to an int
3673
then moves the decimal back to the left 2 places
36.73
I am adding client-side sub-total calculations to my order page, so that the volume discount will show as the user makes selections.
I am finding that some of the calculations are off by one cent here or there. This wouldn't be a very big deal except for the fact that the total doesn't match the final total calculated server-side (in PHP).
I know that the rounding errors are an expected result when dealing with floating point numbers. For example, 149.95 * 0.15 = 22.492499999999996 and 149.95 * 0.30 = 44.98499999999999. The former rounds as desired, the latter does not.
I've searched on this topic and found a variety of discussions, but nothing that satisfactorily addresses the problem.
My current calculation is as follows:
discount = Math.round(price * factor * 100) / 100;
A common suggestion is to work in cents rather than fractions of dollars. However, this would require me to convert my starting numbers, round them, multiply them, round the result, and then convert it back.
Essentially:
discount = Math.round(Math.round(price * 100) * Math.round(factor * 100) / 100) / 100;
I was thinking of adding 0.0001 to the number before rounding. For example:
discount = Math.round(price * factor * 100 + 0.0001) / 100;
This works for the scenarios I've tried, but I am wondering about my logic. Will adding 0.0001 always be enough, and never too much, to force the desired rounding result?
Note: For my purposes here, I am only concerned with a single calculation per price (so not compounding the errors) and will never be displaying more than two decimal places.
EDIT: For example, I want to round the result of 149.95 * 0.30 to two decimal places and get 44.99. However, I get 44.98 because the actual result is 44.98499999999999 not 44.985. The error is not being introduced by the / 100. It is happening before that.
Test:
alert(149.95 * 0.30); // yields 44.98499999999999
Thus:
alert(Math.round(149.95 * 0.30 * 100) / 100); // yields 44.98
The 44.98 is expected considering the actual result of the multiplication, but not desired since it is not what a user would expect (and differs from the PHP result).
Solution: I'm going to convert everything to integers to do my calculations. As the accepted answer points out, I can simplify my original conversion calculation somewhat. My idea of adding the 0.0001 is just a dirty hack. Best to use the right tool for the job.
I don't think adding a small amount will favor you, I guess there are cases where it is too much. Also it needs to be properly documented, otherwise one could see it as incorrect.
working in cents […] would require me to convert my starting numbers, round them, multiply them, round the result, and then convert it back:
discount = Math.round(Math.round(price * 100) * Math.round(factor * 100) / 100) / 100;
I think it should work as well to round afterwards only. However, you should first multiply the result so that the significant digits are the sum of the two sig digits from before, i.e. 2+2=4 decimal places in your example:
discount = Math.round(Math.round( (price * factor) * 10000) / 100) / 100;
Adding a small amount to your numbers will not be very accurate. You can try using a library to get better results: https://github.com/jtobey/javascript-bignum.
Bergi’s answer shows a solution. This answer shows a mathematical demonstration that it is correct. In the process, it also establishes some bound on how much error in the input is tolerable.
Your problem is this:
You have a floating-point number, x, which already contains rounding errors. E.g., it is intended to represent 149.95 but actually contains 149.94999999999998863131622783839702606201171875.
You want to multiply this floating-point number x by a discount value d.
You want to know the result of the multiplication to the nearest penny, performed as if ideal mathematics were used with no errors.
Suppose we add two more assumptions:
x always represents some exact number of cents. That is, it represents a number that has an exact number of hundredths, such as 149.95.
The error in x is small, less than, say, .00004.
The discount value d represents an integer percentage (that is, also an exact number of hundredths, such as .25 for 25%) and is in the interval [0%, 100%].
The error is d is tiny, always the result of correct conversion of a decimal numeral with two digits after the decimal point to double-precision (64 bit) binary floating point.
Consider the value x*d*10000. Ideally, this would be an integer, since x and d are each ideally multiples of .01, so multiplying the ideal product of x and d by 10,000 produces an integer. Since the errors in x and d are small, then rounding x*d*10000 to an integer will produce that ideal integer. E.g., instead of the ideal x and d, we have x and d plus small errors, x+e0 and d+e1, and we are computing (x+e0)•(d+e1)•10000 = (x•d+x•e1+d•e0+e0•e1)•10000. We have assumed that e1 is tiny, so the dominant error is d•e0•10000. We assumed e0, the error in x, is less than .00004, and d is at most 1 (100%), so d•e0•10000 is less than .4. This error, plus the tiny errors from e1, are not enough to change the rounding of x*d*10000 from the ideal integer to some other integer. (This is because the error must be at least .5 to change how a result that should be an integer rounds. E.g., 3 plus an error of .5 would round to 4, but 3 plus .49999 would not.)
Thus, Math.round(x*d*10000) produces the integer desired. Then Math.round(x*d*10000)/100 is an approximation of x*d*100 that is accurate to much less than one cent, so rounding it, with Math.round(Math.round(x*d*10000)/100) produces exactly the number of cents desired. Finally, dividing that by 100 (to produce a number of dollars, with hundredths, instead of a number of cents, as an integer) produces a new rounding error, but the error is so small that, when the resulting value is correctly converted to decimal with two decimal digits, the correct value is displayed. (If further arithmetic is performed with this value, that might not remain true.)
We can see from the above that, if the error in x grows to .00005, this calculation can fail. Suppose the value of an order might grow to $100,000. The floating-point error in representing a value around 100,000 is at most 100,000•2-53. If somebody ordered one hundred thousand items with this error (they could not, since the items would have smaller individual prices than $100,000, so their errors would be smaller), and the prices were individually added up, performing one hundred thousand (minus one) additions adding one hundred thousand new errors, then we have almost two hundred thousand errors of at most 100,000•2-53, so the total error is at most 2•105•105•2-53, which is about .00000222. Therefore, this solution should work for normal orders.
Note that the solution requires reconsideration if the discount is not an integer percentage. For example, if the discount is stated as “one third” instead of 33%, then x*d*10000 is not expected to be an integer.
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
In Java we use the double or float data type to get results in decimal points. However how do i do this in Javascript? The current calculation i am doing is:
a1 += (a1 * results[0][index]) / 100;
EDIT, My Apologises, There was a mistake on my side from using the wrong variables.
All numbers in JavaScript are like Java "double" values. The general problem one encounters in JavaScript is how to do math as if they're not floating-point.
Thus in an expression like yours, if the numerator is not evenly divisible by 100 you'll get a value with a fractional part. You can use "Math.round()" or "Math.floor()" to round or truncate the fraction, but you'll definitely get it.
number.toFixed( \[numberOfDecimals\] )