0

所以我有一些值应该打印为 toFixed(8),但有时会发生该值是带有文本的字符串,因此由于错误而忘记了后面的所有内容(在循环中)。

是否有可能使用 toFixed(8) 如果它可以打印 var 而没有 tofixed?

$.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>

4

2 回答 2

1

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

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

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

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>

于 2018-05-02T19:13:39.223 回答
0

它总是可以的,Number.prototype.toFixed 返回一个字符串表示的结果。

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

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

希望我回答了你的问题

于 2018-05-02T19:00:05.537 回答