0
0

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 1 year has passed since last update.

string型のdecimalをint型に変換する

Last updated at Posted at 2023-05-09

経緯

Web APIの戻り値を整形してDBに保存する処理を実装中。
戻り値に金額(円)が含まれるが、小数点第一位までの値ため、string型になる。
単位が円なことからも、DB保存するときはint型に変換して保存する仕様に決まった。
しかし、以下のように書いたらExceptionが発生してしまった。

c#
string str = "1234.5";
int num = int.Parse(str);

環境

.NET Framework 4.8を使用

原因

公式ドキュメントを確認してみた。

どうやら、小数点を含む数値なのでFormatExceptionが発生するっぽい。

解決策①:decimalに変換→Convert.ToInt32()する

以下の記事を参考に。

解決策①
string str = "1234.5";
int num = Convert.ToInt32(decimal.Parse(str));
Console.WriteLine(num); // 1234

なお、Convert.ToInt32(Decimal)について、公式ドキュメントには以下の記載がある。

最も近い 32 ビット符号付き整数に丸められた value。 value が 2 つの整数のちょうど中間にある場合は、偶数が返されます。つまり、4.5 は 4 に変換され、5.5 は 6 に変換されます。

つまり、偶数丸めという丸め方をするそう。切り捨て/四捨五入/切り上げしたい場合は注意。

解決策②:「.」以降の文字列を切り捨ててint.Parse()する

解決策②
string str = "1234.5";
int indexOfDot = str.IndexOf(".");
string integerStr = str.Substring(0, indexOfDot);
int num = int.Parse(integerStr);
Console.WriteLine(num); // 1234

感想

string型の数値を変換する方法がint.Parse()だけじゃなくて、Convert.ToInt32()もあると気づけたのは良かったです。
解決策①は、明示的にMath.Round()などを書いたほうがいいのか、まだその辺りの判断に迷いますね、、

参考

0
0
4

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?