Home > Software design >  How do I format numbers to add space on thousandth and none on ten thousandth etc
How do I format numbers to add space on thousandth and none on ten thousandth etc

Time:10-03

Let me show that in an example:

What it is:

$ 100,000
$ 10,000
$ 1,000

What I want:

$ 100,000
$  10,000
$   1,000

Also I wasn't sure how to name the question. Any suggestions?

CodePudding user response:

You can use something like in below snippet.

Define a width and text-align to the right

.rich {
  display: inline-block;
  width: 50px;
  text-align: right;
}
<span>$</span><span class="rich">100,000</span><br>
<span>$</span><span class="rich">1,000</span><br>
<span>$</span><span class="rich">100</span><br>

CodePudding user response:

here is a function you can pass the number to and have the desired value, should u need to pass dynamic variables

<?php

function formatNumber($number)
{
    //check string length if it;s not a multiple of three, make it the nearest multiple of three
    $pad =  (floor(strlen(number_format($number)) / 3) * 3)   3;
    $formatted = (strlen($number % 3)) === 0 ?  number_format($number) : str_pad(number_format($number), $pad, " ", STR_PAD_LEFT);
    //echo $formatted . "<br>" . strlen($formatted);
    echo $formatted;
}

formatNumber(127980);
  • Related