PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, August 10, 2022

[FIXED] How to remove zeros from decimal numbers in Javascript

 August 10, 2022     decimal, html, javascript, math, rounding     No comments   

Issue

If the calculation for example is 10/8 the code should answer 1.25 instead of 1.250 or 0/1 should be 0 instead of 0.000. How does one remove zeros from decimal numbers in Javascript while still keeping the max amount of digits (if no zeros) after the dot three (.toFixed(3);)

var operator = ['/'];

function F1() {    
    Z1 = document.getElementById("Z1");
    Z2 = document.getElementById("Z2");
    oper=document.getElementById("operator");
    answer=document.getElementById("answer");
    	
    rZ1 = Math.floor((Math.random()*10));
    rZ2 = Math.floor((Math.random()*10)+1);
    op = operator[Math.floor(Math.random()*1)];
   		
    Z1.innerHTML=rZ1; Z2.innerHTML=rZ2;
    oper.innerHTML=op;
    answer.innerHTML = eval(rZ1 + op + rZ2).toFixed(3);}     
<button onclick="F1()"> New </button>
<p> <label id="Z1"> </label> 
    <label id="operator"> </label>
    <label id="Z2"> </label>
  = <label id="answer"> </label> </p>   


Solution

I'm sure there is a more elegant solution, but this works:

var operator = ['/'];

function F1() {    
    Z1 = document.getElementById("Z1");
    Z2 = document.getElementById("Z2");
    oper=document.getElementById("operator");
    answer=document.getElementById("answer");
    	
    rZ1 = Math.floor((Math.random()*10));
    rZ2 = Math.floor((Math.random()*10)+1);
    op = operator[Math.floor(Math.random()*1)];
   		
    Z1.innerHTML=rZ1; Z2.innerHTML=rZ2;
    oper.innerHTML=op;
    var blah = parseFloat(eval(rZ1 + op + rZ2).toFixed(3));
    if (blah.toFixed(2) == blah) {
      blah = parseFloat(blah.toFixed(2));
      if (blah.toFixed(1) == blah) {
        blah = parseFloat(blah.toFixed(1));
      }
    }
    answer.innerHTML = blah;}
<button onclick="F1()"> New </button>
<p> <label id="Z1"> </label> 
    <label id="operator"> </label>
    <label id="Z2"> </label>
  = <label id="answer"> </label> </p> 



Answered By - Rob Moll
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing