技術(shù)頻道導(dǎo)航
HTML/CSS
.NET技術(shù)
IIS技術(shù)
PHP技術(shù)
Js/JQuery
Photoshop
Fireworks
服務(wù)器技術(shù)
操作系統(tǒng)
網(wǎng)站運(yùn)營

贊助商

分類目錄

贊助商

最新文章

搜索

[解決] C# Parse小數(shù)提示FormatException:輸入字符串的格式不正確

作者:admin    時(shí)間:2022-5-26 20:45:1    瀏覽:

今天在做項(xiàng)目的時(shí)候,遇到Parse小數(shù)拋出異常,提示FormatException:輸入字符串的格式不正確。意思很明確,就是Parse不能用于小數(shù)轉(zhuǎn)換,哪怕是小數(shù)點(diǎn)后面為0,例如100.00這樣的數(shù)據(jù)格式。

C# Parse小數(shù)提示FormatException:輸入字符串的格式不正確

遇到這個(gè)問題,我們可以有兩種解決方法,一種是使用try{}catch(){}方法,另一種是使用TryParse代替Parse方法。

使用try{}catch(){}方法

這個(gè)方法比較傳統(tǒng),是任何程序預(yù)防拋出錯(cuò)誤的普遍做法。

示例

try { 
    int.Parse("100.00");
}
catch (Exception ex) {
    Response.Write(ex.Message .ToString ());
}

輸出

輸入字符串的格式不正確。

我們可以根據(jù)catch的錯(cuò)誤信息,或者有無catch錯(cuò)誤,來判斷程序是否執(zhí)行成功,從而執(zhí)行后面的程序語句。

使用TryParse方法

使用try{}catch(){}方法雖然能解決問題,但總覺得這樣處理一個(gè)字符串轉(zhuǎn)換數(shù)字不是最理想的方法。其實(shí),我們有C#內(nèi)置的方法來專門處理這個(gè)事情,那就是TryParse方法。

繼續(xù)用上面的數(shù)據(jù),使用TryParse方法這樣處理。

string numberStr = "100.00";
int number;

bool isParsable = Int32.TryParse(numberStr, out number);
if (isParsable)
    Response.Write (number);
else
    Response.Write ("不能解析");

TryParse有兩個(gè)功能,當(dāng)解析成功時(shí)就直接返回轉(zhuǎn)換值,當(dāng)解析失敗時(shí)就返回一個(gè)布爾值(truefalse),可謂一舉兩得,是字符串轉(zhuǎn)換為 Int 的最安全方法。

了解TryParse方法

在字符串轉(zhuǎn)換為int的方法中,TryParse方法無疑是最好用的,如果你對(duì)此方法還了解得不夠深入,那么看看下面的介紹。

描述

將數(shù)字的字符串表示形式轉(zhuǎn)換為其等效的 32 位有符號(hào)整數(shù)。返回值指示轉(zhuǎn)換是否成功。

public static bool TryParse (string? s, out int result);

參數(shù)

  • s String:要轉(zhuǎn)換的數(shù)字的字符串。
  • result Int32:當(dāng)此方法返回時(shí),如果轉(zhuǎn)換成功,則包含與s中包含的數(shù)字等效的 32 位有符號(hào)整數(shù)值,如果轉(zhuǎn)換失敗,則返回零。如果s參數(shù)為nullEmpty、格式不正確或表示小于MinValue或大于MaxValue的數(shù)字,則轉(zhuǎn)換失敗。此參數(shù)未初始化傳遞;最初提供的任何值result都將被覆蓋。

返回

  • 布爾值:true,如果s轉(zhuǎn)換成功;否則,false。

例子

下面的示例使用許多不同的字符串值調(diào)用Int32.TryParse(String, Int32)方法。

using System;

public class Example
{
   public static void Main()
   {
      string[] values = { null, "160519", "9432.0", "16,667",
                          "   -322   ", "+4302", "(100);", "01FA" };
      foreach (var value in values)
      {
         int number;

         bool success = int.TryParse(value, out number);
         if (success)
         {
            Console.WriteLine($"Converted '{value}' to {number}.");
         }
         else
         {
            Console.WriteLine($"Attempted conversion of '{value ?? "<null>"}' failed.");
         }
      }
   }
}
// The example displays the following output:
// Attempted conversion of '<null>' failed.
// Converted '160519' to 160519.
// Attempted conversion of '9432.0' failed.
// Attempted conversion of '16,667' failed.
// Converted '   -322   ' to -322.
// Converted '+4302' to 4302.
// Attempted conversion of '(100);' failed.
// Attempted conversion of '01FA' failed.

TryParse(String, Int32)方法在此示例中無法轉(zhuǎn)換的一些字符串是:

  • “9432.0”。轉(zhuǎn)換失敗,因?yàn)樽址荒馨?shù)分隔符;它必須只包含整數(shù)。
  • “16,667”。轉(zhuǎn)換失敗,因?yàn)樽址荒馨M分隔符;它必須只包含整數(shù)。
  • “(100)”。轉(zhuǎn)換失敗,因?yàn)樽址荒馨?dāng)前區(qū)域性的NumberFormatInfo.NegativeSignNumberFormatInfo.NumberNegativePattern屬性定義的負(fù)號(hào)之外的負(fù)號(hào)。
  • “01FA”。轉(zhuǎn)換失敗,因?yàn)樽址荒馨M(jìn)制數(shù)字;它必須只包含十進(jìn)制數(shù)字。 

評(píng)論

TryParse方法與Parse方法類似,只是TryParse方法在轉(zhuǎn)換失敗時(shí)不會(huì)拋出異常。它消除了在s無效且無法成功解析的事件中使用異常處理來測(cè)試FormatException的需要。

s參數(shù)包含多個(gè)形式:

[ws][sign]digits[ws]

方括號(hào)([ 和 ])中的項(xiàng)目是可選的。下表描述了每個(gè)元素。 

元素 描述
ws 可選的空白。
sign 可選標(biāo)志。
digits 從 0 到 9 的數(shù)字序列。

s參數(shù)使用NumberStyles.Integer樣式進(jìn)行解釋。除了十進(jìn)制數(shù)字,只允許前導(dǎo)和尾隨空格以及前導(dǎo)符號(hào)。要顯式定義樣式元素以及可以出現(xiàn)在s中的文化特定格式信息,請(qǐng)使用Int32.TryParse(String, NumberStyles, IFormatProvider, Int32)方法,請(qǐng)看文章詳解C# TryParse怎樣轉(zhuǎn)換小數(shù)、16進(jìn)制、千分位數(shù)字等字符串。

TryParse方法的這種重載將s參數(shù)中的所有數(shù)字解釋為十進(jìn)制數(shù)字。要解析十六進(jìn)制數(shù)字的字符串表示,請(qǐng)調(diào)用Int32.TryParse(String, NumberStyles, IFormatProvider, Int32)重載,請(qǐng)看文章詳解C# TryParse怎樣轉(zhuǎn)換小數(shù)、16進(jìn)制、千分位數(shù)字等字符串。 

總結(jié)

本文介紹了C# Parse小數(shù)提示FormatException:輸入字符串的格式不正確的原因及解決方法,以及深入介紹了TryParse方法的用法。

參考文章

x
  • 站長推薦
/* 左側(cè)顯示文章內(nèi)容目錄 */