开发者

printf, sprintf print at least two decimal places

开发者 https://www.devze.com 2023-01-01 22:08 出处:网络
I\'m trying to figure out how to use sprintf to print at least two decimal places and no leading zeros.For instance

I'm trying to figure out how to use sprintf to print at least two decimal places and no leading zeros. For instance

input:

23
23.0
23.5
23.55
23.555
23.0000

output:开发者_如何学Go

23.00
23.00
23.50
23.55
23.555
23.00

any formatting help would be appreciated


There is no such built-in format specifier. You could check if the number to be printed has two or fewer decimals (round to two decimals and compare), and if so use %.02f. If the number has more decimals, use a %g specifier. Here's an example in Ruby:

def print_two_dec(number)
  rounded = (number*100).to_i / 100.0
  if number == rounded
    printf "%.02f\n", number
  else
    printf "%g\n", number
  end
end

[ 23, 23.0, 23.5, 23.55, 23.555 ].each do |number|
  print_two_dec(number)
end

Outputs:

23.00
23.00
23.50
23.55
23.555


in PHP you could use

<?php
$number = 0.56;
echo sprintf("%0.2f",$number);


In PHP, you may use the number_format function for this purpose, too, which also allows you to change delimiters.


In php this is what I did (inspired by this post). Maybe not the most elegant but... I made a function for printing numbers as strings. I wanted to be able to have flexibility so I have a couple of parameters.

PHP:

function print_num($num,$numdec,$atleast = false,$max_dec = -1)
{

  $ret_norm = false;

  if (!$atleast)
    $ret_norm = true;
  else //atleast = true
  {
    //Want at least $numdec decimals

    //Do we have two or fewer and want to return two or fewer?
    if ($num == ((int)($num*100)/100) & $numdec <= 2 )
      $ret_norm = true;
    else
    {
      //See if we have enough dec. already
      $just_dec = substr((string)$num,strpos((string)$num,".") + 1);
      if ($numdec >= strlen($just_dec))
        $ret_norm = true;
      else
      {
        //More decimals than at least value - make sure we don't go over max if set
        if ( $max_dec >= 0 && strlen($just_dec) > $max_dec )
        {
          //Confine to max_dec length
          $ret_norm = true;
          $numdec = $max_dec;                   //Set for sprintf below
          $num = number_format($num,$max_dec);  //Round the value so doesn't just chop off

        }
        else if ($max_dec >= 0)
          $ret_norm = false;
      } //else
    } //else
  } //else atlest

  if ($ret_norm)
    return sprintf("%0.".$numdec."f",$num);
  else
      return sprintf("%s",$num); //print as is

} //print_num

And to call the function (to have at least two decimals but max 4:

print_num($mynum,2,true,4);

If the number is 34.1, you get 34.10

If the number is 34.12345 you get 34.1235

etc.


Does "23.555".toFixed(2) not do what I think it does? (Javascript)

0

精彩评论

暂无评论...
验证码 换一张
取 消