Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

format a number keeping its sign in php

Is there a way to format in PHP a number always keeping its sign (+ or -)?

In .NET this will be something like:

string myString = number.ToString("+#;#");
like image 663
serhio Avatar asked Mar 04 '10 23:03

serhio


People also ask

What is number format PHP?

The number_format() function is an inbuilt function in PHP which is used to format a number with grouped thousands. It returns the formatted number on success otherwise it gives E_WARNING on failure. Syntax: string number_format ( $number, $decimals, $decimalpoint, $sep )

How do I round to 2 decimal places in PHP?

Example #1 round() examples php echo round(3.4); // 3 echo round(3.5); // 4 echo round(3.6); // 4 echo round(3.6, 0); // 4 echo round(1.95583, 2); // 1.96 echo round(1241757, -3); // 1242000 echo round(5.045, 2); // 5.05 echo round(5.055, 2); // 5.06 ?>

How do you round off decimals in PHP?

The round() function rounds a floating-point number. Tip: To round a number UP to the nearest integer, look at the ceil() function. Tip: To round a number DOWN to the nearest integer, look at the floor() function.


2 Answers

Use sprintf:

$myString = sprintf("%+f", number);
like image 193
Mark Byers Avatar answered Nov 15 '22 04:11

Mark Byers


   $myString = sprintf("%+d", 25);
like image 31
user187291 Avatar answered Nov 15 '22 04:11

user187291



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!