-1

I have an array that displays Date and Conversion. I want to add +"%" after conversion but i cant get it to work. I know as im using an array i cant add this wherever i want. What would be a good way to add + "%" after ConversionRate?

function (data) {
    var tdata = new google.visualization.DataTable();

    tdata.addColumn('date', 'Date');
    tdata.addColumn('number', 'Conversion');

    for (var i = 0; i < data.length; i++) {
        var dateStr = data[i].Date.substr(0, 4) + "-" + data[i].Date.substr(4, 2) + "-" + data[i].Date.substr(6, 2);
        tdata.addRow([new Date(dateStr), Number(data[i].ConversionRate)]);
    }
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
WhoAmI
  • 1,188
  • 6
  • 17
  • 47
  • Have you looked at [formatters](https://developers.google.com/chart/interactive/docs/reference#formatters) (I have no experience with this library - a quick google search found that) – Jamiec Apr 14 '14 at 14:23

2 Answers2

1

This would probably work:

tdata.addRow([new Date(dateStr), Number(data[i].ConversionRate) + "%"]);

But you might have to replace:

tdata.addColumn('number', 'Conversion');

With:

tdata.addColumn('string', 'Conversion');

Or, a better option, as Jamiec mentioned, would be to use the formatter:

var formatter = new google.visualization.NumberFormat({suffix: '%'});
formatter.format(tdata, 0);
Community
  • 1
  • 1
Cerbrus
  • 70,800
  • 18
  • 132
  • 147
  • Thanks, i tried your first suggestion. That's why i thought it was strange. Changing to string gave some errors as im using Google Charts to display the data. I have do it in someother way – WhoAmI Apr 14 '14 at 14:36
  • @KristofferAndersson: Did you try my second suggestion? – Cerbrus Apr 14 '14 at 14:39
-1

Extend javascript's String object...

Like this:

String.prototype.withPct = function(){
  return this + '%';
};

Then use it like this:

var pct = '9';
var withPercent = pct.withPct();

withPercent will be: '9%'

But it looks like you might want to extend Number, in which case, you would:

Number.prototype.withPct = function(){
  return this + '%';
};

Here is a fiddle

J.Wells
  • 1,749
  • 12
  • 13
  • Sorry, how rude of me. [Extending built-in objects is bad pracice](http://stackoverflow.com/questions/14034180/why-is-extending-native-objects-a-bad-practice) also You don't describe how to apply this solution to the actual problem. – Jamiec Apr 15 '14 at 08:01
  • ugh... actually, where i said "then use it like this:" describes how to apply it. also, it's not bad practice... at all. That's how prototypal/prototypical inheritance words. All object literals are created via Object.prototype . – J.Wells Apr 15 '14 at 11:22
  • This was not the best worded or explained question, but it's clearly about the use of `google.visualization.DataTable`. Your answer needed to explain how to get that data table rendering onscreen with your code. – Jamiec Apr 15 '14 at 11:50