Javascript: How to transform float numbers in english format to float numbers in spanish format?

Viewed 282

To build the tables of my website with react I'm using "react-bootstrap-table-next". With this library I can build tables dinamically and order without any problem if numbers are integer or float in english format.

But, If I try to order a table by a column with float numbers in Spanish format, sorting is not correct. This occurs because format of float numbers in javascript are in english format, so to show these values on the screen I have to convert the float number in a string and then I change "." per ",".

In Spanish, we separate the decimal part with a coma not with a dot. For example, 12.95 (english format) === 12,95 (Spanish format)

So, If I try to sort the table by DRE column from higher to lower, as you can see in the next image, sorting is not correct. Because data is really strings and not float numbers due to the change I have to made with them.

Therefore, is there any way to transform float numbers with english format to float numbers in spanish format? Or is there any way to order a column depending the value of another one? For example, I can add to the table the same column but twice. Once in english format and the other in spanish format. The column with english format would not be visible but column with spanish format will be. And this column would be sorted depending of the column in english format.

Is there any way to do that? Or any other alternative?

enter image description here

Edit I

Thanks to @Uby I can sort the table, but not always do the sorting well.

My sorting function is:

sortFunc: (a, b, order) => {
    if (order === 'asc') {
        return parseFloat(a) - parseFloat(b);
    }
    return parseFloat(b) - parseFloat(a); // desc
},

But sorting the table from higher to lower or lower to higher not always the sorting is correct :S

enter image description here enter image description here

Am I doing something wrong? I don't understand what happen that.

2 Answers

Since you're using react-bootstrap-table-next, you can try to write your custom sort function. Here are the docs.

You have to parse the cell content as a flaot (replacing the comma with a dot) and then make a float comparison.

You can define a custom sort function where you parse the Floats yourself and add it to the column definition like this:

{
  // omitted...
  sort: true,
  sortFunc: (a, b, order, dataField, rowA, rowB) => {
      let fA = parseFloat(a.replace(',','.'));
      let fB = parseFloat(b.replace(',','.'));

      if (order === 'asc') {
          return fB - fA;
      }
      return fA - fB; // desc
}
Related