Alphonse
Alphonse

Reputation: 671

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!

Upvotes: 1

Views: 8817

Answers (2)

AlainD
AlainD

Reputation: 6356

variable.toFixed(2)

doc here

  • List item

Upvotes: -2

Jamiec
Jamiec

Reputation: 136084

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

Upvotes: 2

Related Questions