Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript toFixed is not a function

Tags:

javascript

Hi the problem is following:

I define:

var total = 0;

function add(a){
  total+=a;
  var float_num = total.toFixed(2);
  return float_num;
}

The JS give me an error said Uncaught TypeError total.toFixed is not a function

I don't get it. the total I declare is not a number type?

like image 356
user3566769 Avatar asked Dec 09 '22 02:12

user3566769


1 Answers

I think the easiest way to prevent the error from happening is to always parse the parameter as number:

var total = 0;
function add(a){
  total+=a;
  var float_num = Number(total).toFixed(2);
  return float_num;
}
like image 75
HakuteiJ Avatar answered Jan 01 '23 04:01

HakuteiJ