Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Correct way to add space between numbers?

Tags:

php

numbers

space

Probably a simple problem if you know the answer.

What I have

Numbers with no spaces.

$str = 10000;
$str2 = 100000;

What I want

Convert above to below...

$str = '10 000';
$str2 = '100 000';

Own thoughts

I thought of some strpos, regexp, str_replace but is it really the way to solve this? I will accept the most correct, short code answer with no lack of speed.

like image 808
Jens Törnell Avatar asked Mar 28 '13 08:03

Jens Törnell


People also ask

How to add two numbers in PHP?

There are three methods to add two numbers: 1 Adding in simple code in PHP 2 Adding in form in PHP 3 Adding without using arithmetic operator (+). More ...

How do I add a space between text in CSS?

Here are some handy uses of CSS for adding spacing between your content. If you want to place an indent on the first line of a block element like <p>, use the CSS text-indent property. For example, to add an indent of 4 spaces, apply the rule text-indent: 4em; to the element.

How do I add spaces between numbers in Python?

You can add spaces between numbers. It will change the general format of that number. We have two ways of doing that. The first one is the format “ ## ## ## ” and the other one is “ 00 00 00 “. You can choose any of that and implement this to your dataset. It will return you a similar result.

How to add space between two numbers in Excel?

As you can see, we have successfully added space between those numbers. Now, this formula is a combination of three Excel functions. If we want to add any space at a particular place, we need to calculate the position from both the right and left sides. The LEFT function will count the position from the left and extract numbers.


3 Answers

Use number_format function. With space for thoudsandsSparator as below.

number_format($number, 0, '.', ' ')

Codepad Demo.

like image 148
Rikesh Avatar answered Oct 03 '22 02:10

Rikesh


Look no further than number_format.

like image 43
deceze Avatar answered Oct 03 '22 03:10

deceze


use number_format:

$formatted = number_format(
    $number, $numberOfDecimals, $decimalSeperator, $thousandsSeperator);
like image 22
Kris Avatar answered Oct 03 '22 01:10

Kris