如何在Printf函数中将数字除以千位

问题描述 投票:0回答:1

我有一个 C++

printf
函数,我需要将 int 或 double 除以千位数字(每 3 位数字),如下所示:

56 655 666.566 

如果格式化字符串呢?

printf("%.3f",56655666.566)

仅打印:

56655666.566 
c++ format
1个回答
0
投票

正确的解决方案是这样的:

 //Make sure output buffer is big enough and that input is a valid null terminated string
bool pretty_number(const wchar_t *input, wchar_t *output)
{
  if(wcslen(input) >= wcslen(output)) //general checking of buffer size
      return false;
  int pos = 0; //index in output
  if(input[0] == L'+' || input[0] == L'-')
      output[0] = input[0], input++, ++pos;
  int iIntPartLen = wcslen(input);
  for(; iIntPartLen > 0; --iIntPartLen) //find '.'
      if(input[iIntPartLen] == L'.' || input[iIntPartLen] == L',')
          break;
  if(iIntPartLen == 0) iIntPartLen = wcslen(input); //tečka nenalezena

  //first int part
  int i = 0;
  for(; i < iIntPartLen; ++i, ++pos) //i .. input position, pos .. output position
  {
      if((iIntPartLen - i) % 3 == 0 && i != 0)
      {
          output[pos++] = L' ';
      }

      output[pos] = input[i];
  }
  //second decimal part
  if(input[i] == L'.' || input[i] == L',')
  {
      output[pos] = input[i];
      ++iIntPartLen; //přeskočit tečku
      for(; i < wcslen(input); ++i, ++pos) //i .. input position, pos .. output position
      {
          if((i - iIntPartLen) % 3 == 0 && (i - iIntPartLen) != 0)
          {
              output[pos++] = L' ';
          }

          output[pos] = input[i];
      }
  }

 output[pos] = '\0';

}

© www.soinside.com 2019 - 2024. All rights reserved.