Another option instead of using `overflow: hidden` that won't cut off part of a character

My calculator display limits the numbers shown using the CSS property overflow: hidden. However, I don't want it to clip characters in half, which is currently happening.

Mozilla suggests using text-overflow: '';, but this isn't widely supported across browsers. Do you have any alternative suggestions on how to limit the number of characters and clip between characters instead of cutting them off mid-character? (I prefer not to see incomplete numbers on the display)

I'm specifically looking for JavaScript solutions.

Below is my current solution, which only works when inputting numbers and not operators:

  // JavaScript code here
.container {
    /* CSS styles here */
  }
  .wrapper {
    /* More CSS styles here */
  }
  /* Additional CSS rules */
<div class="container">
  <div class="wrapper">
    <!-- Calculator HTML structure -->
  </div>
</div>

Answer №1

If you're dealing with extremely large numbers, you can utilize a combination of a rounding algorithm and exponential notation for their display:

Here is a function that handles the result display:

/**
 * This function uses a specific rounding algorithm to prevent overflow issues with float numbers.
 * If the number exceeds or equals 1e+8, it returns a string representation in exponential form.
 */
function handleResultDisplay(number) {
  number = roundNumber(number, 3);
  return (number >= 1e+8) ? number.toExponential(3) : number;
}

The rounding algorithm in use: [1]

/**
 * An algorithm designed to counter JavaScript's inherent rounding errors.
 * @param  {Number}  num    the number requiring rounding
 * @param  {Number}  scale  the desired number of decimal places
 */
function roundNumber(num, scale) {
  var roundedNum = Math.round(num * Math.pow(10, scale)) / Math.pow(10, scale);
  if (num - roundedNum > 0) {
    return (roundedNum + Math.floor(2 * Math.round((num - roundedNum) * Math.pow(10, (scale + 1))) / 10) / Math.pow(10, scale));
  } else {
    return roundedNum;
  }
}

[1] This algorithm is based on my interpretation of Kunin's answer: Rounding to a Maximum of 2 Decimal Places.

Answer №2

While I understand your preference for JavaScript solutions, there is a more elegant approach using CSS that also maintains the original number for future calculations. Since you have not provided a code snippet, I will assume that your calculator displays the number on a single line.

Here is the solution, assuming the number is displayed with the class .number:

.number {
    display: block;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

By implementing this CSS, the number will be truncated with an ellipsis (...) if it exceeds the space available. For example, it will look like this:

123.486593845674...

This solution is supported by all modern browsers (including IE11 and newer versions).

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

Erase jQuery from the text

I am struggling with splitting or removing text from a filename. For example, if I have filenames like: 200726100_50-0002.JPG 230514008_60-0001.JPG The desired result should be: 230514008_60.JPG 200726100_50.JPG Am I not using the split function cor ...

When the month picker is selected, my intention is to retrieve the true value. However, I am encountering an issue where it consistently returns the false value instead

I created a month picker similar to the image provided. After removing unnecessary code, I was left with only the part that generates questions. Initially, when the month picker renders, no value is selected. However, upon selecting a month, the value is d ...

Issue arises when applying both overflow-x:scroll and justify-content:center

Encountering a problem with using overflow-x: scroll and justify-content: center on a flex parent container. Here is my code snippet: The issue: the first flex child item is not visible as it is cropped on the left side. Please refer to the screenshot and ...

Is there a way to specifically remove only the last row from a table?

Recently, I encountered a problem with my JS code that adds and removes table rows based on user interaction. Adding rows functioned perfectly, but the issue arose when attempting to delete rows. Instead of deleting only the last row as intended, all rows ...

Having issues with my custom AngularJS directive functionality

app.directive("myData", function() { return { templateUrl: '/my-data.html' }; }); my-data.html file code <tr ng-repeat="employee in employees"> <td>{{employee.id}}</td> <td>{{employee.name}}</t ...

What is the best way to obtain a date in the format of yyyy_mm_dd from a datepicker tool?

I am working with 2 datepickers that have similar structures, but different names. The first one has the id "fecha_1_1" and the second one has the id "fecha_1_2". <div class="col-sm-3"> <p>Desde</p> <div class="f ...

Material UI Paper component does not extend to full viewport height

My React component includes a Material UI <Paper> component that acts as a background. This <Paper> is nested inside a <ThemeProvider>, which in turn is nested within a <div>, and then further nested inside the <body>. I have ...

Update the display immediately upon a change in the state

In my app.js file, the code looks like this: export const App = () => { const [selectedMeals, setSelectedMeals] = useState<string[]>(["allItems"]); const onCheckHandler = (e: any) => { const checkedValue = e.target.value; if (e.targ ...

What steps can I take to troubleshoot the cause of my browser freezing when I try to navigate to a different webpage

Within this div, users can click on the following code: <div id="generate2_pos" onclick="damperdesign_payload();" class="button">Generate P-Spectra</div> Upon clicking, the damperdesign_payload() function is triggered, leading to a link to an ...

The art of organizing information: Tables and data management

Looking for a solution with a table: <table> <tr> <td>1</td> <td>2</td> <td>3</td> <td>4</td> </tr> </table> Trying to format the cells to display as: 1 2 3 4 ...

JSONP callback function enables cross-domain communication by allowing a

After delving into the world of JSONP callback functions, I decided to familiarize myself with the concept by researching articles. To further understand JSONP, I uploaded a JSON file onto the server - json file Below is the JavaScript code I used to fet ...

Create a CSS layout with two columns that each take up 50% of the

Is there a way to create a 2 column div with equal width of 50% each, without using floats? Yes, by setting the display property to inline-block. However, a problem arises when attempting to set both columns to exactly 50% - the second div ends up going do ...

Trouble with Google Bar Chart's Background Color not Updating

I'm having issues with the background color in my google Material Charts static api library. Despite entering a specific color code, the change is not being reflected when the page loads. These are the options I have set: var options = { b ...

Is it possible to dynamically toggle the availability of a form text input based on the selected value in a form

I need help with a form on my website. The form has an option to add custom text to clothing you purchase. You can choose yes or no using a selection statement, and there is also an input text field where you can enter the text. I want to make it so that w ...

What is the best way to add content to fill the empty space left after a column has been hidden in a column

Is there a way to automatically adjust the space when a column is hidden by clicking on the legend item? <div id="container" style="height: 300px"></div> <script src="http://code.highcharts.com/highcharts.src.js"></script> var ...

ASP: The submenu items remain visible

I must express my gratitude for the wealth of knowledge this site has provided me with. It has been an invaluable resource for me this year, even though I have scoured every corner and still come up empty-handed. Allow me to simplify the situation at hand ...

Executing a message in Azure Service Bus using Javascript/Node.js

I am utilizing the @azure/service-bus library in a Node.js application to receive messages. The code I am using is as follows: const { ServiceBusClient } = require("@azure/service-bus"); const sbClient = new ServiceBusClient(connectionString); ...

Ensuring a @keyframe animation remains constant for the entire duration of the user's visit to the webpage using CSS

How can I create a continuous @keyframe animation that stays active for the duration of the user's visit to my webpage? I've implemented several color animations on my website, each with a specific duration. Is there a way to make these color ch ...

Struggling with converting my menu design into a dropdown menu

Recently completed creating my initial menu with a left navigation bar design. Wondering if it is achievable to implement a dropdown effect on hover without the use of javascript? I have come across several solutions but they do not seem to work for me, po ...

Bridging the gap between the user interface and server

I'm developing a React Native app that requires user registration and authentication. I've successfully implemented a POST request to communicate with a mongoose server and store data in MongoDB. At this point, my goal is to enable users to input ...