Input field value - remove leading zeros

59,589

Solution 1

More simplified solution is as below. Check this out!

var resultString = document.getElementById("theTextBoxInQuestion")
                           .value
                           .replace(/^[0]+/g,"");

Solution 2

str.replace(/^0+(?!\.|$)/, '')

  '0000.00' --> '0.00'   
     '0.00' --> '0.00'   
  '00123.0' --> '123.0'   
        '0' --> '0'  

Solution 3

var value= document.getElementById("theTextBoxInQuestion").value;
var number= parseFloat(value).toFixed(2);

Solution 4

It sounds like you just want to remove leading zeros unless there's only one left ("0" for an integer or "0.xxx" for a float, where x can be anything).

This should be good for a first cut:

while (s.charAt(0) == '0') {            # Assume we remove all leading zeros
    if (s.length == 1) { break };       # But not final one.
    if (s.charAt(1) == '.') { break };  # Nor one followed by '.'
    s = s.substr(1, s.length-1)
}

Solution 5

Ok a simple solution. The only problem is when the string is "0000.00" result in plain 0. But beside that I think is a cool solution.

var i = "0000.12";
var integer = i*1; //here's is the trick...
console.log(i); //0000.12
console.log(integer);//0.12

For some cases I think this can work...

Share:
59,589

Related videos on Youtube

Samuel Liew
Author by

Samuel Liew

Useful Stack Overflow userscripts for everyone: Searchbar & Nav Improvements advanced search, search bookmarks, link to meta/main in sidebar Post Headers & Question Table of Contents sticky post headers and vote buttons, list of all answers in right sidebar Review Queue Helper skip audits, keyboard shortcuts, auto suggest close reason, auto focus dialog submit New Comments Layout better comment readability (username and date on a new line, etc.) Reduce Clutter hides many unnecessary things like podcast announcement banners, better duplicates revision list, strips analytics tracking from the site, fix broken avatar images Chat Improvements the only and best chat userscript To learn more about my userscripts, see the readme file on the repo. The Stack Exchange Timeline

Updated on November 01, 2021

Comments

  • Samuel Liew
    Samuel Liew over 2 years

    I have a textbox in Javascript. When I enter '0000.00' in the textbox, I want to know how to convert that to only having one leading zero, such as '0.00'.

    • ChronoFish
      ChronoFish over 11 years
      Need to clarify what a "string" is. If your "string" is an decimal number, then the answer will be different than if your "string" is a text string. "00000.000" -> "0.000" would be a decimal conversion. "000TXT10001" -> "0TXT10001" would require a trim function. For instance what are you expecting when the input is "0011.1100" -> "011.1100" or "11.11"?
  • Eric
    Eric over 13 years
    Does this cause any issues if the number of zeros to the left of the decimal is very large?
  • Julian Young
    Julian Young over 12 years
    Eric's got a point, it will only work if you have one leading zero. Any more than that and fail.
  • Kaleb Anderson
    Kaleb Anderson over 8 years
    This is a good solution. Relying on built-in functions is not always the best option. I would turn this into a helper function that takes a string argument and returns the formatted string.
  • Andrew Tobilko
    Andrew Tobilko over 7 years
    @MikeM, then you could use replace(/^[0]+/g, "0")
  • Gaston
    Gaston over 6 years
    Works very well for me. I would just advise to add a piece of code to support negative numbers (with "-" in first character).
  • DarkMukke
    DarkMukke over 5 years
    Can you please elaborate. Also is it possible not to post pictures ? Image links can break while text will always be there.
  • Krishna Jonnalagadda
    Krishna Jonnalagadda about 5 years
    Really great solution, which i am looking
  • jneuendorf
    jneuendorf about 4 years
    @MikeM Could someone please elaborate? From my understanding of regexes and as of regexr.com/4tn79 the used regex does not match the zero in the 3rd example, but the function does indeed work for all the examples (using Chrome). So how does the 3rd example work if the regex does not match correctly?! And how can I be sure it will always work?
  • SherylHohman
    SherylHohman over 2 years
    Stackoverflow guidelines state to not post pics of text, code, data, or error messages. That including text output for code. Many reasons why: pics of text can be difficult to read, especially on mobile devices, it can cause unnecessary data download for metered cellular data, it cannot be copy-pasted or searched, and it is not accessibility friendly. Good uses of pics are when the issue describes a graphical issue that cannot be described in words. Please delete the unnecessary pic to meet SO guidelines.