所以我有一些值应该打印为 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>
最佳答案
您可以使用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>
关于javascript 打印 tofixed 如果不可能则打印正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50141643/