4

I'm using echarts to graph float values and I want to round the decimal numbers to 2 decimal places in the tooltip from the series (keeping the current tooltip style).

My option var is:

var truckTurnAroundTimeOption = {
  color: ['dodgerblue', '#e67e22'],
  title: {
    text: 'Truck Turnaround Time',
    show: false,
    textStyle: {
      fontFamily: 'Roboto',
      fontSize: 14
    }
  },
  tooltip: {
    trigger: 'axis'
  },
  calculable: true,
  xAxis: [
    {
      type: 'category',
      boundaryGap: false,
      axisLabel: {
        formatter: function (value, index) {
          return value.slice(0,5);
        }
      },
      data: truckTurnaroundTimes.map(item => item.hour)
    }
  ],
  yAxis: [
    {
      type: 'value',
      name: 'mins',
      nameLocation: 'middle',
      nameGap: 30,
      
      splitLine: {
        //remove grid lines
        show: false
      }
    }
  ],
  grid: {
    left: 68,
    top: 8,
    right: 28,
    bottom: 38
  },
  legend: {
    show: true,
    icon: 'circle',
    orient: 'vertical',
    top: -4,
    right: 26,
    itemHeight: 12,
    textStyle: {
      fontSize: 11,
    }
  },
  series: [
    {
      name: 'current',
      type: 'line',
      smooth: false,
      data: data.map(item => parseFloat(item.current_truck_turnaround_time)) /* Values like 12.2343443, 5.123452 */
    },
    {
      name: 'improved',
      type: 'line',
      smooth: false,
      data: data.map(item => parseFloat(item.improved_truck_turnaround_time)) /* Values like 12.2343443, 5.123452 */
    }
  ]
};

The data in the array datasets contain values like: 12.2343443, 5.123452, etc.

PD: I don't want to round the series data before graphing

Eduardo G
  • 370
  • 4
  • 17

3 Answers3

2

Use the toFixed()-method of parseFloat() here:

data.map(item => parseFloat(item.current_truck_turnaround_time).toFixed(2))
  • 1
    The post says "I don't want to round the series data before graphing", which this answer does. It doesn't appear that eCharts has a way to format only the tooltip series values without building the entire tooltip from scratch. This answer may work, but what if you wanted to format a number as a string, e.g. a currency like $1,432.21 or percent like 32.4%? – Andrew Aug 03 '21 at 17:30
2

You just need to add the valueFormatter to your tooltip object like so:

{     
  tooltip: {
    trigger: 'axis',
    valueFormatter: (value) => value,
   }
}
HalesEnchanted
  • 615
  • 2
  • 9
  • 20
  • This is the correct answer, as of eCharts 5.3: https://echarts.apache.org/handbook/en/basics/release-note/5-3-0 – Andrew Jul 11 '22 at 21:10
1

You can provide a formatter function to format the display to the required precision.

{
  tooltip: {
    formatter([{value: v1}, {value: v2}]) => `${v1.toFixed(2)}<br/>${v2.toFixed(2)}`,
    trigger: 'axis'
  }
}
osamu
  • 983
  • 1
  • 9
  • 13