开发者

Dropping the '.00' when printing floats that hold whole numbers

开发者 https://www.devze.com 2022-12-30 02:29 出处:网络
I\'m currently displaying开发者_Python百科 a quantity in Javascript. I want it to display (for example) the whole number as 89 instead of 89.00; however, if the number is fractional like 89.50 then it

I'm currently displaying开发者_Python百科 a quantity in Javascript. I want it to display (for example) the whole number as 89 instead of 89.00; however, if the number is fractional like 89.50 then it should display 89.50


It isn't clear if your question is about parsing floats or about checking integers. Here is a function that accepts numbers or strings and returns the float formatted as a string:

function displayQuantity(n) {
  return parseFloat(n).toFixed(n%1 ? 2 : 0);
}

In case you have to support (very) old browsers, look here for an implementation of Number#toFixed.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号