javascript 打印到固定,如果不可能则打印正常

javascript print tofixed and if not possible print normal

所以我有一些值应该打印为 toFixed(8),但有时该值是一个带有文本的字符串,因此由于错误,它后面的所有内容(在循环中)都被遗忘了.

是否有可能使用 toFixed(8) 如果可以的话,否则打印没有 tofixed 的 var?

$.each(trades, function(_, obj) {
  if (obj['sold'] == true) {
    if (obj['enddate'] === undefined) {
      count = 1
      profit = obj['profit_percentage']
      tradeList.add({
        startdate: obj['datetime'],
        if (typeof obj['buyprice'] === "number") {
          buyprice: obj['buyprice'].toFixed(8)
        }
        else {
          buyprice: obj['buyprice']
        }
      });
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

总是可以的,Number.prototype.toFixed return是结果的字符串表示。

所以,0.123.toFixed(2) 实际上是一个字符串 '0.12'。 如果你想让它变成一个数字,使用一元加法:+0.123.toFixed(2) will return a number 0.12.

其他情况,如果你输入的不是数字,那就另当别论了。

希望我回答了你的问题

您可以使用 typeof 检查当前值是否是可以使用 toFixed on- 的数字,只要您的数字不是字符串即可。

var myMixedData = ["string", 0.3434, .434234434533422, "anotherString", .2434242];

myMixedData.forEach(function(thing) {
  if (typeof thing === "number") {
    console.log(thing.toFixed(8));
  } else {
    console.log(thing);
  }
});

在看到您的代码后,这里有一个更详细的答案,可能会有更多帮助。我不确定 obj tradeList 是什么类型,但这里是一个对象数组。

var trades = [{"sold": true,"datetime": "date1","buyprice": 23.343252}, {"sold": true,"datetime": "date2","buyprice": "justAStringHere"}];

var tradeList = [];

$.each(trades, function(_, obj) {
  if (obj['sold'] == true) {
    if (obj['enddate'] === undefined) {
      count = 1;
      //profit  = obj['profit_percentage']
      var tradeListObj = {};
      tradeListObj.startDate = obj['datetime'];
      
      var buyprice = obj['buyprice'];
      if (typeof buyprice === "number") {
        buyprice = buyprice.toFixed(8);
      }
      
      tradeListObj.buyprice = buyprice;
      tradeList.push(tradeListObj);
    }
  }
});

console.log(tradeList);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>