I am working with HighChart and I need to format a currency value in a specific format.
Example -> XX.XXX.XXX, XX €
I am using this function in highchart to format the value correctly:
formatter: function () {
return parseFloat (this.total, 10) .toFixed (2) .replace (/ (\ d) (? = (\ d {3}) + \.) / g, '$ 1,'). toString () + ' € ';
}
The problem is that I am not getting the points and commas to match as I intend.
Example for values:
Given -> 1052325
Expected -> 10.523,25 €
Current value obtained -> 10,523.25
I could do a new replace() and change the commas for the points, but I would like to know how to do it right away at REGEXP.
Thank you very much
Ok. I cant use some of the functions in HighChart.
I try this code in the ppotaczek example
Highcharts.chart('container', {
series: [{
data: [1052325],
dataLabels: {
enabled: true,
formatter: function() {
var originalString = parseFloat(this.y, 10).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$ 1,').toString();
var finalPriceString = originalString.split('');
var finalPriceStringLenght = finalPriceString.length;
var rowtoChange = finalPriceStringLenght - 3;
finalPriceString[rowtoChange] = 'I';
var lastString = finalPriceString.join('') + ' €';
alert(lastString);
}
}
}]
});
The code works in the Fiddle example, but it doesn't work when I put it in the Highchart Json.
I tried another approach now, I always have this string format so I just want to replace the third character from the end of the string.
For this I am using this replace with regexp:
stringFormated.replace(/.$/,',');
It works and replaces well. The problem is that it is always at the last character of the string. I wanted it to go to the third character after the end of the string.
Best regards
Related
This question already has answers here:
Calculate string value in javascript, not using eval
(12 answers)
Closed 4 months ago.
When the text was '2+3+5+1', the logic was easy
Split('+') so the string is converted to an array.
loop over the array and calculate the sum.
check the code below
void main() {
const text = '2+3+5+1';
final array = text.split('+');
int res =0;
for (var i=0; i<= array.length -1; i++){
res+=int.parse(array[i]);;
}
print(array);
print(res);
}
Now this String "2+3-5+1" contains minus.
how to get the right response using split method?
I am using dart.
note: I don't want to use any library (math expression) to solve this exercice.
Use the .replace() method.
text = text.replace("-", "+-");
When you run through the loop, it will calculate (-).
You can split your string using regex text.split(/\+|\-/).
This of course will fail if any space is added to the string (not to mention *, / or even decimal values).
const text = '20+3-5+10';
const arr = text.split(/\+|\-/)
let tot = 0
for (const num of arr) {
const pos = text.indexOf(num)
if (pos === 0) {
tot = parseInt(num)
} else {
switch (text.substr(text.indexOf(num) - 1, 1)) {
case '+':
tot += parseInt(num)
break
case '-':
tot -= parseInt(num)
break
}
}
}
console.log(tot)
I see 2 maybe 3 options, definitely there are hundreds
You don't use split and you just iterate through the string and just add or subtract on the way. As an example
You have '2+3-5+1'. You iterate until the second operator (+ or -) on your case. When you find it you just do the operation that you have iterated through and then you just keep going. You can do it recursive or not, doesn't matter
"2+3-5+1" -> "5-5+1" -> "0+1" -> 1
You use split on + for instance and you get [ '2', '3-5', '1' ] then you go through them with a loop with 2 conditions like
if(isNaN(x)) res+= x since you know it's been divided with a +
if(!isNaN(x)) res+= x.split('-')[0] - x.split('-')[1]
isNaN -> is not a number
Ofc you can make it look nicer. If you have parenthesis though, none of this will work
You can also use regex like split(/[-+]/) or more complex, but you'll have to find a way to know what operation follows each digit. One easy approach would be to iterate through both arrays. One of numbers and one of operators
"2+3-5+1".split(/[-+]/) -> [ '2', '3', '5', '1' ]
"2+3-5+1".split(/[0-9]*/).filter(x => x) -> [ '+', '-', '+' ]
You could probably find better regex, but you get the idea
You can ofc use a map or a switch for multiple operators
I have the following data
firstData = [
["2019-11-24", "12:38:54"],
["2019-11-21", "07:06:29"],
["2019-11-20", "19:26:37"],
["2019-09-26", "19:56:00"] ]
secondData = [
["2019-09-26", "10:26:00"],
["2019-11-20", "06:52:34"],
["2019-11-21", "07:06:19"],
["2019-11-24", "07:38:54"] ]
I would like to display graph like this.
date and time graph
So as I mentioned in the comment the y value must be a number. If you want to render it as a time format you will need to convert this string into a proper number, check the function below and the demo: https://jsfiddle.net/BlackLabel/2vc7aphd/1/
function parseToNumber(string) {
return Date.parse("1-1-1 " + string) - Date.parse('1-1-1 00:00:00')
}
function parseData(data) {
let output = [];
data.forEach(d => {
let x = d[0],
y = d[1];
output.push({
name: x,
y: parseToNumber(y),
label: y
});
})
return output;
}
I'm using Highcharts and need to chart data with quarterly frequency using a format like 'yyyy Q#'.
I found how to format the periods in the tooltip (using a JS formatter function) and would now like to use the same format in the rangeSelector 'From' and 'To' input fields.
From the documentation I see I could use 'inputDataFormat', but that has the standard PHP strftime formatter function, which does not cover my requirement.
Any idea appreciated!
Massimo
It is possible to extend Highcharts format. You need to define Highcharts.dateFormats object:
Highcharts.dateFormats = {
Q: function(timestamp) {
var date = new Date(timestamp),
y = date.getFullYear(),
m = date.getMonth();
return y + '.Q' + (Math.floor(m / 3) + 1);
}
};
And then you can use 'Q' to format timestamp.
rangeSelector: {
inputEnabled: true,
inputDateFormat: '%Q'
},
example: http://jsfiddle.net/twcu0djj/
I'm using dotnet.highcharts to generate a chart.
If I do not set any label formatting on the y-axis labels, this is what is displayed.
This is good.
So 200M = 200,000,000
And it looks like this is done automatically.
If I wanted to put a $ in front of the value and I use:
function() { return '$' + Highcharts.numberFormat(this.value, 0) ; }
Then the label will now display $200,000,000.
How would i get the format to display it with the short form with the dollar sign like $200M ?
thanks.
Unfortunately in this case, you have to either take the pre formatted label, or rebuild the level of abbreviation you want in the formatter yourself.
In this case, you could something like
yAxis: {
labels: {
formatter: function() {
return '$'+this.value / 1000000 + 'M';
}
}
},
According to this stackoverflow post, you can call the original formatter with:
this.axis.defaultLabelFormatter.call(this);
Put this code before call the chart
Highcharts.setOptions({
lang: {
thousandsSep: ','
}
});
Highcharts does a great job auto-formatting dates both on the x-axis and in tooltips. Unfortunately I need a custom function to format my y-values, and /plotOptions/line/tooltip/pointFormat accepts only a format string and not a function, so I have to set /tooltip/formatter instead. How do I get hold of the formatted date (e.g. Oct'13 or 20. Oct) as shown on the x axis? I don't seem to have access to point.key from there, only the raw millis value.
http://jsfiddle.net/9Fke4/
You can use dateFormat()
tooltip: {
formatter: function() {
return '<b>' + Highcharts.dateFormat('%b\' %d',this.x) + ':</b> ' + this.y;
}
},
http://jsfiddle.net/9Fke4/1/
FWIW, this was answered in a Highcharts issue on Github
formatter: function() {
var tooltip = this.series.chart.tooltip,
item = this.point.getLabelConfig(),
header = this.series.chart.tooltip.tooltipFooterHeaderFormatter(item);
return header + this.y;
}
Corresponding fiddle:
http://jsfiddle.net/9Fke4/12/
If you are using a shared series:
tooltip: {
formatter: function (tooltip) {
var header,
s = [];
$.each(this.points, function(i, point) {
if(header == null) {
var config = point.point.getLabelConfig();
header = tooltip.tooltipFooterHeaderFormatter(config);
}
s.push(point.y);
});
return header + s.reverse().join('<br>');
},
shared: true
}
conver the raw milliseconds to a date object using
var currentDate = new Date (tome in milliseconds)
in the tootip/formatter function you have defined.
this will give you good control over the date. you can use currentDate.getMonth(), getDate(), getDay(), etc methods to get the information you want from that date.
build a string with the above info and return.
I hope this will help you.
The solution I ended up with is to pre-format the y-values and store them as part of the series data; the pre-formatted values can then be referenced from the tooltip headerFormat and pointFormat, where they can be used along with {point.key}, which contains the auto-formatted date (and which is not available when providing a custom tooltip formatter):
http://jsfiddle.net/uG3sv/