我有一个角度代码,可以从谷歌财务中获取数据。但是,如果存在代表数百万和数千的M或K,它可以正确获取 vo 和 avvo 的数据。如果没有它,则无法正确显示该值。
如何正确处理这两种情况?
示例数据如下。第一个有浮点数据,第二个有M,我认为是字符串。我可以正确显示字符串但浮动不正确。它将显示为N / A和avvo为2.000。我想在数据中显示确切的值
// [
{
"id": "549805688244420"
,"t" : "AZG"
,"vo" : "0.00"
,"avvo" : "2,087.00"
}
]
和
// [
{
"id": "381558643124633"
,"t" : "U11"
,"vo" : "1.34M"
,"avvo" : "2.47M"
}
]
以下是我的代码:
angular.module('myapp.factories').factory('$stockDataFactory',
['$q', '$filter', '$webServicesFactory',
function ($q, $filter, $webServicesFactory) {
return {
getStockDetails: function (stock) {
var deferred = $q.defer();
$webServicesFactory.getNotParsed(
"https://www.google.com/finance/info",
{},
{
infotype: "infoquoteall",
q: stock.market+":"+stock.symbol
}
).then(
function success(response) {
response = JSON.parse("["+response.replace(/\r?\n|\r/g, ' ').split('[').splice(1,1)[0]);
stock = response[0];
var formatedData = {
volume: stock.vo,
averageDailyVolume: stock.avvo
};
HTML:
<div class="row row-center">
<div class="col boldText">Volume: </div>
<div class="col col-21">{{stock.volume || 'N/A'}}</div>
<div class="col boldText">Avg. Vol: </div>
<div class="col col-21">{{(stock.averageDailyVolume | shrinkNumber: 2) || 'N/A'}}</div>
</div>
js中的shrinkNumber
angular.module('chaishen.factories').filter("shrinkNumber", function($filter) {
return function(number, fractionSize) {
if(number === null) return null;
if(number === 0) return "0.000";
// default number of decimals for values >1000 or <-1000 if not set in view
if(!fractionSize || fractionSize < 0)
fractionSize = 1;
var abs = Math.abs(number);
var rounder = Math.pow(10,fractionSize);
var isNegative = number < 0;
var key = '';
var powers = [
{key: "Q", value: Math.pow(10,15)},
{key: "T", value: Math.pow(10,12)},
{key: "B", value: Math.pow(10,9)},
{key: "M", value: Math.pow(10,6)},
{key: "K", value: 1000}
];
for(var i = 0; i < powers.length; i++) {
var reduced = abs / powers[i].value;
//reduced = Math.round(reduced * rounder) / rounder;
reduced = Math.round(abs * rounder) / rounder;
if(reduced >= 1){
abs = reduced;
key = powers[i].key;
break;
}
}
if(number >= 1000) {
//return abs + key;
return abs;
}
else if(number <= -1000) {
//return '-' + abs + key;
return '-' + abs;
}
else {
//return $filter('number')(((isNegative ? '-' : '') + abs + key), 3);
return $filter('number')(((isNegative ? '-' : '') + abs), 3);
}
};
});