0

Apologies for asking what looks like a comment asked question but I cannot seem to be able to solve.

How do I write 0.2 to round to eight decimal places and make it with the different color, such as belows

enter image description here

Could anyone tell me how to solve ??

Thank you very much!

Sylvia
  • 257
  • 2
  • 6
  • 16

1 Answers1

1

You need to follow these steps:

  1. Create a fixed string representation of the number using toFixed(8) which gives you 8 decimal places.
  2. Get the substring to separate it into two parts as you desired to apply different color to each part.
  3. Create a span element for that each parts and add a class to them.
  4. Add this final HTML in your web page.

function changeNum(elemId, num){
  var fixed8 = num.toFixed(8);
  var substrWhite = fixed8.substr(0, fixed8.indexOf('.')+3);
  var substrGrey = fixed8.substr(fixed8.indexOf('.')+3, fixed8.length);
  var nHTML = "<span class='white'>"+substrWhite+"</span><span class='grey'>"+substrGrey+"</span>"
  document.getElementById(elemId).innerHTML = nHTML;
}

var num = 0.2;
changeNum('content1', num);
num = 0.56;
changeNum('content2', num);
num = 0.123;
changeNum('content3', num);
.white{
  color: white;
}
.grey{
  color: grey;
}
div{
  background: #444;
}
<div id='content1'></div>
<div id='content2'></div>
<div id='content3'></div>
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62