【问题标题】:Printing nice large numbers c++ on IOS [duplicate]在IOS上打印漂亮的大数c ++ [重复]
【发布时间】:2012-12-30 11:52:29
【问题描述】:

我正在寻找一种打印大数字的好方法,以便它们更具可读性

即 6000000

应该是

6.000.000

6,000,000 取决于地区

更新

我在我的代码上尝试了以下操作(在 IOS 上)

char* localeSet = std::setlocale(LC_ALL, "en_US");
cout << "LOCALE AFTER :" << std::locale("").name() << endl;

localeSet 始终为 NILL

我总是得到“LCOALE AFTER: C”

【问题讨论】:

标签: c++ objective-c boost


【解决方案1】:

在标准 C++ 中是这样的:

template < class T >
std::string Format( T number )
{
    std::stringstream ss;
    ss << number;
    const std::string num = ss.str();
    std::string result;
    const size_t size = num.size();
    for ( size_t i = 0; i < size; ++i )
    {
        if ( i % 3 == 0 && i != 0  )
            result = '.' + result;
        result = ( num[ size - 1 - i ] + result );
    }
    return result;
}

...
long x = 1234567;
std::cout << Format( x ) << std::endl;
...

【讨论】:

  • 您是否查看过 cmets 中链接的问题,该问题早在您发布答案之前就已存在?为什么不在循环中使用字符串流,或者为什么索引比迭代器/流操作更好?为什么你一遍又一遍地复制result 而不是使用push_back()
  • 另外:你的代码对于一些负数来说是错误的,例如-100000 -&gt; -.100.000.
猜你喜欢
  • 2017-05-01
  • 1970-01-01
  • 2013-01-20
  • 1970-01-01
  • 1970-01-01
  • 2011-10-29
  • 2012-01-24
  • 2010-09-13
相关资源
最近更新 更多