hack のためのネタ帳, etc,,,

Thousands Separator と言うか、いわゆる 3 桁区切りとか 1,000 区切りとか千の位のコンマと言うか、位取りと言うか

printf

SUSv2 に対応してると flag に ' を与えると桁区切りしてくれる模様。
printf("%'d", 1234567890);
2010-12-07 現在 Ubuntu 10.04 で確認する限りにおいて Ruby 1.8.7 の format では SUSv2 の flag には対応出来てない模様
関数でやるとこんな感じか?
def ts x; x.to_s =~ /^([^.]*\d)(\d{3}(\.|$))/ ? x = ts($1)+","+$2+$' : x; end

関連

Ruby 版のデッドコピーだけどこんな感じか?
function ts(x){
  var y,z;
  return x.toString().match(/^([^.]*\d)(\d{3}(\.|$))/)
    ? (y = RegExp.$2, z = RegExp.rightContext, x = ts(RegExp.$1) + "," + y + z)
    : x;
}
再帰すると RegExp が上書きされるので、計算順序に注意しながら若干工夫する必要があるみたい。
std::ostringstreamstd::locale 食わせると良いらしい。
多分こんな感じ。
#include <string>
#include <sstream>
#include <locale>
template<class T> inline const std::string ts(T v)
{
  std::ostringstream oss;
  oss.imbue(std::locale(""));
  oss << std::fixed << v;
  return oss.str();
}

参考:
追記: 2018-10-15
Cygwin だと libstdc++ のコンパイルオプションが腐ってるらしく std::locale が "C" と "POSIX" 以外食わせると runtime_exception 吐くので、現時点でこの方法は使えない模様。
関連:
String::Format Method を使うと Excel の書式指定と同じ方式で出来るようだ。
  • MSDN Library / NET Development / .NET Framework 4.6 and 4.5 / Development Guide / Application Essentials / Base Types / Formatting Types / Custom Numeric Format Strings # The "," Custom Specifier
これは VB とか VBA 由来かな?
C++ でも CLR でコンパイルすると使えるっぽいけど。

コメントをかく


「http://」を含む投稿は禁止されています。

利用規約をご確認のうえご記入下さい

Wiki内検索

フリーエリア

管理人/副管理人のみ編集できます