how to mandate a number to display 2 decimal places? - javascript

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 );

Related

Javascript How to convert a decimal number to a string with specific number of decimal places

In a javascript code, I have a requirement to format a decimal number to a specific number of decimal places and get its exact string representation. For example, If the number is 999999999.9 and the number of decimal places is 8, then the expected value should be "999999999.90000000"
When the Number.toFixed(8) is used it returns a rounded value which is not what I want. Please refer the below code
var num = 999999999.9
var string_rep = num.toFixed(8)
>> the value of string_rep is "999999999.89999998"
I used num.toString() and tried to manually format the decimal part by adding/removing digits, but it does not work for very small numbers like "0.00000008" as the function toString() returns
the scientific notation, i.e. something like "9e-8"
So what should be the proper approach for this?
Number.prototype.toLocaleString will do the trick
num.toLocaleString('en-US', {minimumFractionDigits: 8, useGrouping: false})//"999999999.90000000"

toFixed function on large numbers

I have following number with e+ on it
9.074701047887939e+304
I want to take only 9.07
So I tried below , but its not working , its returning full output
console.log(parseFloat(9.074701047887939e+304).toFixed(2));
Ps : I also need the code to work for normal numbers aswell for example 892.0747010 , should output 892.07
toFixed trims digits after the decimal point, but your actual number is very large - it doesn't have a decimal point.
If you don't know in advance whether the number is large or not, one option is to call toFixed(2) on the number first (trimming off and properly rounding digits past the decimal point for small numbers), then using a regular expression to take the numeric part only (removing the e if it exists), then call toFixed(2) again (trimming off and properly rounding digits past the decimal point for large numbers):
const fix = num => Number(
num.toFixed(2).match(/\d+(?:\.\d+)?/)[0]
).toFixed(2);
console.log(fix(9.074701047887939e+304));
console.log(fix(123.4567));
console.log(fix(12345));
Since you mentioned for both 9.074701047887939e+304 and 9.074701047887939, you want the answer to be 9.07.
For 9.074701047887939e-304 I assume you want 9.07 too, although you might actually want 0.00.
const twoDecimal = (a =>
(a.toString().match(/e/) ? Number(a.toString().match(/[^e]*/)[0]) : a).toFixed(2)
);
console.log(twoDecimal(9.074701047887939e+304));
console.log(twoDecimal(9.074701047887939e-304));
console.log(twoDecimal(9.074701047887939));
console.log(twoDecimal(789.074701047887939));
console.log(twoDecimal(0.00001));
console.log(twoDecimal(0.20001));
console.log(twoDecimal(-9.074701047887939e+304));
console.log(twoDecimal(-9.074701047887939e-304));
console.log(twoDecimal(-9.074701047887939));
console.log(twoDecimal(-789.074701047887939));
console.log(twoDecimal(-0.00001));
console.log(twoDecimal(-0.20001));
console.log(twoDecimal(0));

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

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

Using toFixed(2) in JavaScript is producing undesired results

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.

Categories

Resources