Rob Monhemius
Rob Monhemius

Reputation: 5144

How do I style numbers?

I am trying to change the styling of numbers.

//test for success . . . do not remove
if(document.getElementById('number').innerHTML !== "1000"){
  alert('Wrong answer, you changed the number!!!');
}
<p id="number">1000<p>

<p>The 1000 above should show up like 1 000<p>

Upvotes: 3

Views: 1282

Answers (3)

AstonishGong
AstonishGong

Reputation: 21

This is simple and easy:

const numberFormat = (x) => {
  return x.replace(/(.{4})/g, "$1 ");
}

Upvotes: 0

user943702
user943702

Reputation: 954

I suggest to use display:flex so that the "sep" character is in auto-determined font-size.

The idea is that turn <p>1000</p> into <p><span>1</span><span>0</span><span>0</span><span>0</span></p> by js.

Then, add "sep" character visually by css generated content. span:nth-last-of-type(3n) { content:<sep>; ..}. This way, the <sep>(can be any character actually) will have same font-size as number text.

demo

Upvotes: 0

kiranvj
kiranvj

Reputation: 34107

Try something like this.

const numberWithSep = (x) => {
  return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, "<div class='sep'></div>");
}

var num = numberWithSep('12345678');


document.getElementById("number").innerHTML = num;

//retrive like this
console.log(document.getElementById("number").innerText);
.sep {
  display: inline-block;
  padding: 10px;
}
<p id="number"><p>

If you want the separator as comma (,) just change the div to ,

Upvotes: 1

Related Questions