Using toFixed(2) in JavaScript is producing undesired results - javascript

I'm doing this:
var refundAmount = parseFloat($('#refundAmount2').val().replace('$',''));
var refundReceived = $('#refundReceived');
var remainderAmount = refundAmount-parseFloat(refundReceived.val().replace('$',''));
alert(parseInt(remainderAmount).toFixed(2));
No matter what I do, the result always ends with 2 decimal places being '.00'. So if the first number is 200.12 and the second is 100.08, it should be alerting me with 100.04 but instead I get 100.00.
Why might this be happening?

You used parseInt to convert that number to an integer and then used toFixed(2) to convert it to a number with 2 decimal places. Adding 2 decimal places to an integer will always result in .00.
Try
alert(remainderAmount.toFixed(2));
See DEMO.

You're getting it as an int with parseInt(), then doing the toFixed(). So you're putting decimal places on an int.

Related

Javascript - Converting a number to two decimal places while keeping zeros

I have number without decimal places and I want to convert it to two decimal places (while keeping zeros) and keep its number type.
I have tried it like this:
$scope.invoice_data.form_data.items_shipping_handling = parseFloat(($scope.invoice_data.form_data.items_shipping_handling).toFixed(2));
console.log(typeof $scope.invoice_data.form_data.items_shipping_handling);
But it parseFloat doesn't take into account decimal places if they are zeros.
So if I have 2 I want to convert it to 2.00 //number.
Thank you for your time. I mention that the code is in angular so if it is any angular way of doing it I am open to suggestions.
Details: I cannot simply use toFixed(2) I need the result to have decimal places but to keep its number format, toFixed() converts it to string. I need it to be of number type!
Numbers dont have a "number of decimal places" - they're internally just a series of 1's and 0's. To display a number to a set number of decimal places you can use toFixed
var value = 2;
console.log(value.toFixed(2));
If you're trying to round a number to a set of decimal places one way is to multiply by 100, round it and then divide by 100
var value = 2.123456
var rounded = Math.round(value*100)/100;
console.log(rounded);
variable.toFixed(2)
doc here
List item

Display "$xx.90" instead of "$xx.9" in Javascript

When I use p=10000 ,r=15 and n=60 in the below ...
var x = parseFloat((Math.round(r/12/100*p/(1-Math.pow(1+ +(r/12/100),-n))*100)/100).toFixed(2));
x = 237.9 instead of 237.90.
If the combo of p, r and n result in a number that is not $xx.x", then the code snippet works fine ...ie. formats to 2 decimal places.
But why is it displaying 237.9 instead of 237.90?
When you call number.toFixed(2), you do indeed get a string representation of the number with two decimal digits:
var number = 237.9;
number.toFixed(2); // '237.90'
However, when you then use parseFloat on this, you convert it back to a number again; since a number does not contain information about the number of zeros to display, the last zero is dropped as it is printed:
parseFloat(number.toFixed(2)); // 237.9
To avoid this, simply don't convert your string back into a float, but use it as a string.
var x = parseFloat((Math.round(r/12/100*p/(1-Math.pow(1+ +(r/12/100),-n))*100)/100)).toFixed(2);
p=10000,r=15, n=60;
var x = parseFloat((Math.round(r/12/100*p/(1-Math.pow(1+ +(r/12/100),-n))*100)/100)).toFixed(2);
console.log(x)
Add toFixed after all operations. You need string, basically...

Javascript format number of decimal places in float

Can anybody help me with this issue i'm having? I'm using the following code to get the value of an input field
parseFloat($("#salaryFrom").val());
The only problem is that if the value in the salaryFrom field ends with a 0 it's getting cut of from the results. e.g. The value 8.50 is being returned as 8.5 and I need it to return 8.50
As a float 8.50 an 8.5 are identical. However when you convert your number to a string you can specify the number of decimal places you would like to use with the function toFixed() e.g.
var a = parseFloat($("#salaryFrom").val());
var b = a.toFixed(2);
The function toFixed() takes the number of decimal places you would like to format your number to, in this case 2.
Javascript has a toFixed() function to format floats. So do try that.
tmp = parseFloat($("#salaryFrom").val());
formatted_val = tmp.toFixed(2);
alert(formatted_val);
Use .toFixed(2) in javascript. (2) - its optional The number of digits after the decimal point. Default is 0 (no digits after the decimal point)
var num = 8.5;
console.log(num.toFixed(2))
Example: Using toFixed
var numObj = 12345.6789;
numObj.toFixed(); // Returns '12346': note rounding, no fractional part
numObj.toFixed(1); // Returns '12345.7': note rounding
numObj.toFixed(6); // Returns '12345.678900': note added zeros
(1.23e+20).toFixed(2); // Returns '123000000000000000000.00'
(1.23e-10).toFixed(2); // Returns '0.00'
2.34.toFixed(1); // Returns '2.3'
-2.34.toFixed(1); // Returns -2.3 (due to operator precedence, negative number literals don't return a string...)
(-2.34).toFixed(1); // Returns '-2.3' (...unless you use parentheses)

How can I parse a string as an integer and keep decimal places if they are zeros?

I have these strings: "59.50" & "30.00"
What I need to do is convert them to integers but keep the trailing zeros at the end to effectively return:
59.50
30.00
I've tried:
Math.round(59.50 * 1000) / 1000
Math.round(30.00 * 1000) / 1000
but ended up with
59.5
30
I'm assuming I need to use a different method than Math.round as this automatically chops off trailing zeros.
I need to keep these as integers as they need to be multiplied with other integers and keep two decimals points. T thought this would be fairly straight forward but after a lot of searching I can't seem to find a solution to exactly what I need.
Thanks!
Your premise is flawed. If you parse a number, you are converting it to its numerical representation, which by definition doesn't have trailing zeros.
A further flaw is that you seem to think you can multiply two numbers together and keep the same number of decimal places as the original numbers. That barely makes sense.
It sounds like this might be an XY Problem, and what you really want to do is just have two decimal places in your result.
If so, you can use .toFixed() for this:
var num = parseFloat("59.50");
var num2 = parseFloat("12.33");
var num3 = num * num2
console.log(num3.toFixed(2)); // 733.64
Whenever you want to display the value of the variable, use Number.prototype.toFixed(). This function takes one argument: the number of decimal places to keep. It returns a string, so do it right before viewing the value to the user.
console.log((123.4567).toFixed(2)); // logs "123.46" (rounded)
To keep the decimals - multiply the string by 1
example : "33.01" * 1 // equals to 33.01
Seems you are trying to retain the same floating point, so better solution will be some thing like
parseFloat(string).toFixed(string.split('.')[1].length);
If you want numbers with decimal points, you are not talking about integers (which are whole numbers) but floating point numbers.
In Javascript all numbers are represented as floating point numbers.
You don't need the trailing zeros to do calculations. As long as you've got all the significant digits, you're fine.
If you want to output your result with a given number of decimal values, you can use the toFixed method to transform your number into a formatted string:
var num = 1.5
var output = num.toFixed(2) // '1.50'
// the number is rounded
num = 1.234
output = num.toFixed(2) // '1.23'
num = 1.567
output = num.toFixed(2) // '1.57'
Here's a more detailed description of toFixed: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed

how to mandate a number to display 2 decimal places?

I'm aware that the way to truncate a number to 2 decimal places in toFixed(). However, in case the number has just 1 decimal place, I get an error.
What is the way to mandate a number to display >2 decimal places(numbers after the decimals will be 0 in this case) so that toFixed() will not throw an error?
This should work on any input:
var result = Math.round(original*100)/100;
Generally, I would avoid using toFixed(), as it can behave unexpectedly when given non float input. Also, see here:
How to format a float in javascript?
Trying to format number to 2 decimal places jQuery
I think you are trying to apply toFixed on a string ? You could just parse it into a float before using toFixed on it.
var a = '1.0';
a = parseFloat( a );
a = a.toFixed(2);
console.log( a );

Categories

Resources