Formatting of large numerical values with jQuery

I have a huge table with numbers and other data. I want to color the large numbers based on their value in decimal, hundreds, thousands, and millions.

For example:

<tr>
   <td class="numColour">20,000,365.00 ISK</td>
   <td class="numColour">2,467,218,928.46 ISK</td>
   <td class="numColour">498,356.65 ISK</td>
</tr>

All the numbers are in a TD class=numColour. I want to format them like this:

<tr>
   <td class="numColour"><span class="red">20</span>,<span class="blue">000</span>,<span class="green">365</span>.<span class="white">00</span> ISK</td>
   <td class="numColour"><span class="yellow">2</span>,<span class="red">467</span>,<span class="blue">218</span>,<span class="green">928</span>.<span class=white">46</span> ISK</td>
   <td class="numColour"><span class="blue">498</span>,<span class="green">356</span>.<span class="white">65</span> ISK</td>
</tr>

I initially added spans to the numbers like this:

$('.numColour').each(function(){
    var tempVal = $(this).html();
    tempVal = tempVal.replace(' ISK', '</span> ISK').replace('.', '</span>.<span>').replace(/,/g, '</span>,<span>');
    tempVal = "<span>" + tempVal;
    $(this).html(tempVal);
});

But I'm having trouble figuring out how to add the classes based on the number value. For instance, fractions should be white, hundreds should be green, thousands should be blue, millions should be red, and hundreds of millions should be yellow.

I'm stuck. Any help would be greatly appreciated. Thank you.

Answer №1

Here is the solution that worked perfectly for me:

let colors = ['dog', 'cat', 'mouse', 'hamster'];
$('td.numColor').html(function () {
    let input = $(this).text();
    let numbers = input.split(' ');
    let decimal = '<span class="frac">' + numbers[0].split('.')[1] + "</span>";
    let frontPart = numbers[0].split('.')[0].split(',');
    for (let i = frontPart.length - 1, j = 0; i >= 0; i--, j++) {
        frontPart[i] = '<span class="' + colors[j] + '">' + frontPart[i] + '</span>'
    }
    finalOutput = frontPart.join(',') + '.' + decimal + ' ' + numbers[1];
    return (finalOutput)
})

Check out the jsFiddle example for reference

Answer №2

While not the most efficient solution, here are some functions to help you get started. DEMO

HTML

<table id="numbers">
  <tr>
    <td class="numColour">20,000,365.00 ISK</td>
  </tr>
  <tr>
    <td class="numColour">2,467,218,928.46 ISK</td>
  </tr>
  <tr>
    <td class="numColour">498,356.65 ISK</td>
  </tr>
</table>

CSS

body {
  background: #666;
  color: #999;
}

.numColour {
  font-family: monospace;
}

.fraction {
  color: #fff;
}

.int-group-1 {
  color: #00c800;
}

.int-group-2 {
  color: #0000c8;
}

.int-group-3 {
  color: #c80000;
}

.int-group-4 {
  color: #c8c800;
}

.int-group-5 {
  color: #00c8c8;
}

JavaScript

var SEPARATOR_DECIMAL_US_EN = '.';
var SEPARATOR_GROUP_US_EN = ',';

var normalizeNumberFromString = function(s, decimalSeparator) {
  var intParts;
  decimalSeparator = decimalSeparator || SEPARATOR_DECIMAL_US_EN;
  var normalized = s.trim().replace(/[^0-9.]/g, "");
  var parts = normalized.split(decimalSeparator);
  return {
    intPart: parts[0],
    fractionPart: parts[1]
  }
}

var separateIntIntoReversedGroups = function(i) {
  var parts = [];
  var part;
  i = parseInt(i, 10);

  while (i > 0) {
    part = i % 1000;
    parts.push(part);
    i = parseInt(i / 1000, 10);
  }
  return parts;
}

var padNum = function(n, pad, len) {
  var i = 0;
  var padLength;
  var s = '';

  n = '' + n;

  pad = '' + pad;
  pad = pad.charAt(0) || ' ';

  if (n.length >= len) {
    return '' + n;
  }

  padLength = len - n.length;
  for (i; i < padLength; ++i) {
    s = s + pad;
  }
  s = s + n;
  return s;
}

var formatStringFromSeparatedNumber = function(reversedIntGroups, fractionPart, groupSeparator, decimalSeparator) {
  var g, i, intGroups = [], numGroups = reversedIntGroups.length, s = '';

  groupSeparator = groupSeparator || SEPARATOR_GROUP_US_EN;
  decimalSeparator = decimalSeparator || SEPARATOR_DECIMAL_US_EN;

  for (i = reversedIntGroups.length - 1; i >= 0; i--) {
    g = '<span class="int-group-' + (i+1) + '">';
    if (i < reversedIntGroups.length - 1) {
      g += padNum(reversedIntGroups[i], 0, 3);
    } else {
      g += reversedIntGroups[i];
    }
    g += '</span>';
    intGroups.push(g);
  }
  s = intGroups.join(groupSeparator);
  s = s + decimalSeparator + '<span class="fraction">' + fractionPart + '</span>';
  return s;
};

var formatNumberString = function(s) {
  var parts, reversedIntGroups;
  parts = normalizeNumberFromString(s);
  reversedIntGroups = separateIntIntoReversedGroups(parts.intPart);
  return formatStringFromSeparatedNumber(reversedIntGroups, parts.fractionPart, ',', '.');
};

var replaceWithFormattedNumber = function(i, el) {
  var $el = $(el);
  var v = $el.html();
  v = formatNumberString(v);
  console.log('v::', v);
  $el.html(v);
};

$(document).ready(function() {
  $('.numColour').each(replaceWithFormattedNumber);
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to choose a child div using jQuery

<div class='class1'> <div class='class2'> <div class='class3'> some unique text </div> <div class='class5'> more unique text </div> </div> < ...

Enhance user experience with a dynamic Bootstrap combo box that updates based on

I am currently facing an issue with the bootstrap combobox plugin. I am having trouble changing the selection and sending that information from the view to the controller. $('#MyCombo').on('change', function () { var data = $(this) ...

Is it possible to edit the HTML DOM of an external URL that is opened using window.open?

Imagine a scenario where I have a page located at: www.mydomain.com When a user clicks on a button, it triggers the opening of a new window using: newWin = window.open("https://www.otherdomain.com","a","height=800,width=1000"); Now, my objective is to m ...

After making an AJAX call, the table data can be found in page 1 under the tbody

Can anyone help me with this issue? I've gone through all the guides related to this problem and followed them step by step, but still no success. After populating the table using an AJAX call, all the data appears on a single page only. I attempted ...

Using jQuery to retrieve the value of an input with a designated class name

Is there a way to retrieve all values from input type text fields with a particular class name? I gave this code a shot, however, it didn't produce the desired result. $('input .classname').each(function(){ console.log($(this).val()); ...

Creating a Masonry Slider with varying heights and widths of images is a simple and effective way to showcase diverse content in a visually

I am looking to implement a unique grid image slider that accommodates images of varying heights and widths. I envision something similar to the example shown below. The image showcases a pattern where the sliders alternate between square images and two r ...

Creating a dropdown menu using jQuery

I have a situation where I am linking a dropdown menu to the "onChange" event of a textbox. The functionality works as expected, however, when I click the button associated with it, the click event is not triggered. Below is the script being used: <sc ...

Error: The expression #categories_id(categories) cannot be identified due to a syntax error

Trying to use the id with brackets in jQuery is resulting in an error $("#categories_id(categories)").val("hello"); Output: An error occurred: Syntax error, unrecognized expression: #categories_id(categories) ...

Angular 2/Typescript experiencing a glitch with Jquery carousel functionality

After properly installing and importing jquery in my project, I encountered a specific issue. Within my application code, there is a line that reads as follows: $('#myCarousel').carousel("next"); Upon running npm start, an error is thrown: ...

Customizing the date format in jQuery datepicker for ASP.NET applications

I need help changing the date format to dd-MM-yyyy in my jQuery date picker. Currently, it is set to MM-dd-yyyy and I've tried modifying the code below in asp webforms but it's not working: <link href="../Contents/css/jquery-ui.css" rel="styl ...

Can you identify the selected item on the menu?

My goal is to highlight the menu item for the current page by adding a "current" class. I've tried several code snippets from this website, but most of them didn't work as expected. The code I'm currently using almost works, but it has a sma ...

Suggestions for integrating an Autocomplete plugin into the CK classic editor 5 for ASP .net core MVC

In this scenario, I am incorporating the classic CK-Editor into a C# View file. My goal is to include a new autocomplete plugin in the classic editor. <div class="card-body areacls cardBox" contenteditable="true" id="@are ...

Determining the Height of a Navigation Bar Automatically with CSS

My website is built using React and react-strap. I set up my .header-overlay to cover the entire background within the .header. However, due to the presence of the .navbar, the .header-overlay extends beyond the boundaries of the .header vertically. I tho ...

Move the final column from one table to another table given a specific criterion

I have a task where I need to extract the last column from table3 and transfer it into table4. For example, consider table3: Names Process_id Total construction 1 1111 construction_1 1 0000 engineering 1 22 ...

Turn off the ability to view the content of .css and .js files within the browser

Earlier, I inquired about how to disable file and folder listing and discovered that it can be achieved using a file named .htaccess. To disable folder listing, I entered Options -Indexes in the .htaccess file located in the parent folder. Additionally, to ...

Tips for creating sliding header content alongside the header

Is it possible for the content in the header to scroll up, displaying only the navigation list and hiding the logo when a user scrolls on the website? Currently, while the header background slides up, the content within the header remains in place. I feel ...

Interactive search functionality using jQuery

In the panel I have, I would like to include a search input field that allows users to type in a word. As soon as a match is found, that specific word will be highlighted within the panel while the other information disappears. ...

Using Ajax post to retrieve data from multiple tables in PHP and MYSQL

I'm attempting to achieve the following: Retrieve TMSGUID from the Campuses table using the ID (primary key). Retrieve TMSGUID from the Sites table. Retrieve ID and Description from the SiteOrganisation table by using Site GUID. The PHP page is bei ...

Tips for eliminating annoying white space on petite gadgets with css programming?

Having an issue with my static html page where I am seeing white space on the right side when checking responsiveness. I have tried multiple solutions found here on stack overflow, including adding the following code: I attempted to add this inline: html ...

Mysterious and never-ending loop that seems to loop endlessly and eludes my

My prototype includes a method for adding callbacks: /* * Add a callback function that is invoked on every element submitted and must return a data object. * May be used as well for transmitting static data. * * The callback function is supposed to e ...