Trimming decimal points from large numbers using Javascript

Having trouble with a function that is supposed to format numbers in a more visually appealing way. It's glitchy - for example, 400 displays as 4H, which is correct. However, 430 displays as 4.3H, which is acceptable, but then 403 displays as 4.03H, which is not ideal. Here is my code, and I'm unsure how to fix it.

EDIT: When larger numbers come into play, like 5003 displaying as 5.003K instead of just 5K, it creates issues. I want all numbers to display properly without excess decimals. For instance:

5000 -> 5K
5500 -> 5.5k
5050 -> 5.05k
5005 -> 5K

 <!-- Slight modifications made to the code block below for uniqueness -->
                var ranges = [
                    { divider: 1000000000000000000000000000000000 , suffix: 'Dec' },
                    { divider: 1000000000000000000000000000000 , suffix: 'Non' },
                    // Other range objects remain unchanged
                ];
                
                // Function remains unchanged
            
.wrapper {
  position: fixed;
  top: 35%;
  left: 35%;
}
<!-- HTML content here -->

Answer №1

It seems like there are some issues in your code

  1. if (rounded == true), the input value from the number field will never be true.
  2. INP(num, true) - you are passing true as an argument, which is not expected according to your code. The expected parameter should be a number.
  3. if (round == null) is also always false. If the second input field is empty, the value would be an empty string and not null. Therefore, it should be changed to if (round == '')

var ranges = [{
  divider: 1000000000000000000000000000000000,
  suffix: 'Dec'
}, {
  divider: 1000000000000000000000000000000,
  suffix: 'Non'
}, {
  divider: 1000000000000000000000000000,
  suffix: 'Oct'
}, {
  divider: 1000000000000000000000000,
  suffix: 'Sep'
}, {
  divider: 1000000000000000000000,
  suffix: 'Sex'
}, {
  divider: 1000000000000000000,
  suffix: 'Quin'
}, {
  divider: 1000000000000000,
  suffix: 'Quad'
}, {
  divider: 1000000000000,
  suffix: 'T'
}, {
  divider: 1000000000,
  suffix: 'B'
}, {
  divider: 1000000,
  suffix: 'M'
}, {
  divider: 1000,
  suffix: 'K'
}, {
  divider: 100,
  suffix: 'H'
}];

function INP(number, round) {
  for (var i = 0; i < ranges.length; i++) {
    if (number >= ranges[i].divider) {
      if (round == '') {
        return (number / ranges[i].divider) + ranges[i].suffix;
      } else {
        var res = (number / ranges[i].divider).toFixed(round),
          fr = res - parseInt(res, 10);
        return (fr > 0 ? res : parseInt(res, 10)) + ranges[i].suffix;
      }
    }
  }
  return number.toString();
}
.wrapper {
  position: fixed;
  top: 35%;
  left: 35%;
}
<div class="wrapper">
  <input type="number" id="num" placeholder="number">
  <br>
  <input type="number" id="rounded" placeholder="round">
  <div id="output"></div>
</div>
<script>
  var field = document.getElementById("num");
  var div = document.getElementById("output");

  field.onkeyup = function() {
    var num = document.getElementById("num").value;
    var rounded = document.getElementById("rounded").value;

    var output = INP(num, rounded);

    div.innerHTML = "Output: " + output;
  }
</script>

Answer №2

You are facing two issues.

Initially, using if (rounded == true) is not achieving the desired outcome. Since rounded is a string, comparing it to a boolean results in the boolean being converted to a string, leading to the string value of "1". Therefore, it is essentially the same as if (rounded == "1"). To rectify this, you can utilize parseInt() to transform the input into an integer, followed by using if (rounded).

Secondly, the issue was arising from not passing the actual value of rounded to INP, rather supplying true. Consequently, when utilized in toFixed(), it ended up converting to the integer 1, thus consistently rounding to one decimal place instead of basing it on the input value within rounded.

To eliminate any additional trailing zeroes from the result generated by toFixed, invoke parseFloat() on it to convert it back to a number.

var ranges = [
    { divider: 1000000000000000000000000000000000 , suffix: 'Dec' },
    { divider: 1000000000000000000000000000000 , suffix: 'Non' },
    { divider: 1000000000000000000000000000 , suffix: 'Oct' },
    { divider: 1000000000000000000000000 , suffix: 'Sep' },
    { divider: 1000000000000000000000 , suffix: 'Sex' },
    { divider: 1000000000000000000 , suffix: 'Quin' },
    { divider: 1000000000000000 , suffix: 'Quad' },
    { divider: 1000000000000 , suffix: 'T' },
    { divider: 1000000000 , suffix: 'B' },
    { divider: 1000000 , suffix: 'M' },
    { divider: 1000 , suffix: 'K' },
    { divider: 100 , suffix: 'H' }
];

function INP(number, round) {
  for (var i = 0; i < ranges.length; i++) {
    if (number >= ranges[i].divider) {
      if (round == null) {
        return (number / ranges[i].divider) + ranges[i].suffix;
      } else {
        return parseFloat((number / ranges[i].divider).toFixed(round)) + ranges[i].suffix;
      }
    }
  }
  return number.toString();
}

var field = document.getElementById("num");
var div = document.getElementById("output");

field.onkeyup = function() {
  var num = parseInt(document.getElementById("num").value, 10);
  var rounded = parseInt(document.getElementById("rounded").value, 10);

  if (rounded) {
    var output = INP(num, rounded);
  } else {
    var output = INP(num);
  }

  div.innerHTML = "Output: " + output;
}
.wrapper {
  position: fixed;
  top: 35%;
  left: 35%;
}
<div class="wrapper">
  <input type="number" id="num" placeholder="number">
  <br>
  <input type="number" id="rounded" placeholder="round">
  <div id="output"></div>
</div>

Answer №3

To determine the unit prefix, one can utilize logarithm of 10 for calculation. Make sure to adjust it accordingly.

var ranges = { 33: 'Dec', 30: 'Non', 27: 'Oct', 24: 'Sep', 21: 'Sex', 18: 'Quin', 15: 'Quad', 12: 'T', 9: 'B', 6: 'M', 3: 'K', 2: 'H' };

function INP(number, round) {
    var exp = Math.floor(Math.log(number) / Math.log(10));
    while (exp > 3 && !ranges[exp]) {
        exp--;
    }
    if (!ranges[exp]) {
        return number.toString();
    }
    return round === '' ?
        (number / Math.pow(10, exp)) + ranges[exp] :
        (number / Math.pow(10, exp)).toFixed(round) + ranges[exp];
}
.wrapper {
  position: fixed;
  top: 35%;
  left: 35%;
}
<div class="wrapper">
  <input type="number" id="num" placeholder="number">
  <br>
  <input type="number" id="rounded" placeholder="round">
  <div id="output"></div>
</div>
<script>
  var field = document.getElementById("num");
  var div = document.getElementById("output");

  field.onkeyup = function() {
    var num = document.getElementById("num").value;
    var rounded = document.getElementById("rounded").value;

    var output = INP(num, rounded);
    div.innerHTML = "Output: " + output;
  }
</script>

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

Sending the value of "username" between two components within Angular 2

I have a good understanding of nesting child components within parent components in Angular 2, but I'm a bit unclear on how to pass a single value from one component to another. In my scenario, I need to pass a username from a login component to a cha ...

Having trouble integrating Socket.io with Express.js?

I'm currently attempting to connect socket.io with express.js: var socket = require('./socket_chat/socket.js'); var express = require('express'), app = module.exports.app = express(); var io = require('socket.io&apo ...

Transmit HTML message using the "textarea" tag through email

Whenever I try to send the content of my "textarea" via email, it always ends up being sent as a blank message. How can I fix this issue? Below is my PHP code: <?php $input = json_decode(file_get_contents("php://input"), true); $ToEmail = "<a href ...

The JavaScript-generated form element will not be included in the data submitted through the POST method

While it may appear that this question has been asked before, my specific inquiry seems to be unique as I have not found a similar answer in other threads. Therefore, I am initiating a new discussion. My issue revolves around a form which contains a link ...

Updating a column in a SQL Table via an Ajax request

I am attempting to store the on or off value from a form into an SQL database by calling a JS function with an AJAX request that sends it to a PHP page for processing. I seem to be facing some issues with my code and could really use some assistance as the ...

Updating the value of an HTML table cell when the data in local storage is changed using JavaScript

In my JavaScript code, I have a function that retrieves data from an API and stores it in the browser's localStorage. The API fetches ETA data and saves it in localStorage using the key id_ETA (e.g., 12342_ETA). I want the values in the HTML table&a ...

The automated test locator in Angular using Protractor is failing to function

I am facing a challenge with my angular web application as there are some elements that are difficult to interact with. One specific element is a checkbox that needs to be checked during testing: ` <div class="row form-group approval_label"> < ...

Encountering both a CORS error and data in Angular 7

My application is using Angular 7 for the front end and Node.js (express) for the backend. The cors module in the Node.js server.js file is implemented like this: var cors = require('cors') app.use(cors()); When making an API call from the fro ...

Avoiding redundant code in React Components: Best practices to keep your code DRY

I am currently utilizing React with Material UI v1.0 to implement a list, but I want to avoid code repetition. Here is the existing code: import List from 'material-ui/List'; import DashboardIcon from 'material-ui-icons/Dashboard'; ...

Tips for merging two applications into a single file using Node.js

This code snippet represents the functionality of my chat application. var worker = function(worker) { var http = require('http'); var fs = require('fs'); var app = http.createServer(function(request, response) { f ...

using JavaScript to strip away content following .jpg

var lochash = "#http://www.thepresidiumschool.com/news_image/102%20NRD_7420.jpg&lg=1&slide=0"; I am looking to eliminate or modify the content that comes after .jpg. ...

Can an internal/private function call a public function?

Just wondering if I'm missing something here, as I tried the following: (function() { var thing = function() { var doIt = function() { console.log("just do it"); this.updateValue(5); }; return { ...

Exploring the transformation of asynchronous callbacks to promises in Node.js

As a novice, I am currently in the process of developing a User Management system using NodeJS. Previously, I had implemented it with MongoDB and Express, but now I am rebuilding it with Express, Sequelize, and Postgresql to enhance my understanding of cer ...

The information seems to not be getting transferred to the req.body variables from the HTML form

Within my server-side settings using knex and express, I have defined the following function: // POST: Create new users app.post('/add-user', (req, res) => { const {firstName, lastName, emailAdd, gender, dob, password} = req.body; cons ...

Having trouble loading an image after successfully connecting to an API with react.js

I've been working on a custom fetch component to load images from the "the dog API" onto my page. However, I'm facing some issues with getting the images to display correctly. Can anyone spot what might be missing in my setup? App.js import &apo ...

The animation in Rive feels sluggish when navigating to a page with animation in Blazor WASM, despite implementing dispose methods

After attempting to display river animation on the index page using Blazor WASM (basic template), I encountered some performance issues. When navigating back and forth between the Counter page and the index page, I noticed that after around 20 clicks, the ...

Tips on deleting specific elements from an array by utilizing the splice method

Here are the details of my first array: [ { members: [ '60ee9148104cc81bec3b97ab' ] } ] And this is the second array: [{"_id": "60ee9148104cc81bec3b97ab","username": "user1", "email": "< ...

Can someone assist me in retrieving the information stored within an object?

I'm currently working on a Discord bot and I am in need of the user ID, specifically 'xxx', but I'm unsure of how to retrieve it. Here is what I have tried so far: n.mentions.users.User. -- n.mentions.users.User() This is what my code ...

Using AJAX to update content based on selected value in a dropdown menu

My challenge lies in ensuring that a select box retains the selected value from a database entry and triggers an onchange event during form editing or updating. While I have successfully populated the data in the select box based on other selections, I a ...

Stop observing IntersectionObserver within the React.useEffect function

I'm attempting to retrieve the top and bottom measurements from multiple elements using the IntersectionObserver. However, once I have the measurements, I'm unsure how to stop observing the elements. The issue is that each element has a position ...