3
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

文字の書式

Last updated at Posted at 2017-02-07

目的

C#とpython3での文字書式を入れる方法

参考にしたサイト

ありがとうございました。

Csharp

python3

0詰め,ゼロパディング(zero padding),リーディングゼロパディング

123=>「0123」
↑のような感じにするやつ
色々見つかった。

C#版

var num1 = 123;
//ToString 
num1.ToString("D4");
num1.ToString("0000");
num1.ToString(new string('0', 4));
//string.Format
string.Format("{0:0000}", num1);
string.Format("{0,04:D}", num1);
//$""
$"{num1:d4}";
$"{num1:0000}";

python3版

'{:04}'.format(123)
'{:0>4}'.format(123)
str(123).zfill(4)

ゼロサプレス(zero suppress) ,リーディングゼロサプレス

123=>「 123」(先頭にスペースで4文字)
↑のような感じにするやつ
C#

var num1 = 123;
string.Format("{0,4}", num1);// 123
string.Format("{0,4:D}", num1);//
$"{num1,4}";
$"{num1,4}";

python3

'{:4}'.format(123)
'{:>4}'.format(123)

小数点

123.456 => 「123.5」(小数点一桁かつ四捨五入)
↑のような感じにするやつ
がメインだけどそうでないものも
C#

var d = 123.456;
d.ToString("#.#");//123.5
d.ToString("0.0");//123.5
d.ToString("0000.0");//0123.5
d.ToString("0.00");//123.46
d.ToString("N1");//123.5
d.ToString("F1");//123.5
string.Format("{0:F1}",d);//123.5
string.Format("{0:N1}", d);//123.5
string.Format("{0:0.0}", d);//123.5
string.Format("{0:#.#}", d);//123.5
$"{d:0.0}"; //123.5
$"{d:#.#}"; //123.5
$"{d:f1}"; //123.5
$"{d:n1}"; //123.5

python3

'{:.1f}'.format(d)//123.5
3
6
5

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?