TryStrToFloat - C++ Builder

C++ Builder 参考手册System::SysutilsTryStrToFloat


字符串转浮点数值

头文件:#include <System.SysUtils.hpp>
命名空间:System::Sysutils
函数原型:

bool __fastcall TryStrToFloat(const System::UnicodeString S, System::Extended &Value);
bool __fastcall TryStrToFloat(const System::UnicodeString S, System::Extended &Value, const TFormatSettings &AFormatSettings);
bool __fastcall TryStrToFloat(const System::UnicodeString S, double &Value);
bool __fastcall TryStrToFloat(const System::UnicodeString S, double &Value, const TFormatSettings &AFormatSettings);
bool __fastcall TryStrToFloat(const System::UnicodeString S, float &Value);
bool __fastcall TryStrToFloat(const System::UnicodeString S, float &Value, const TFormatSettings &AFormatSettings);

参数:

  • S:字符串;
  • Value:输出浮点数转换结果;
  • AFormatSettings:地区格式;

返回值:

  • true:转换成功,通过参数 Value 返回浮点类型数值转换结果;
  • false:转换失败;
  • 如果没有 AFormatSettings 参数,小数点使用全局变量 FormatSettings.DecimalSeparator,
    不同国家或地区的小数点也不同,例如:中国和美国使用小圆点 '.',法国和越南使用逗号 ',';
    如果 FormatSettings 被修改,可以用 Sysutils::GetFormatSettings(); 恢复默认值为本地格式;
  • 如果有 AFormatSettings 参数,小数点使用 AFormatSettings.DecimalSeparator;
  • 函数 StrToFloatStrToFloatDef 和 TryStrToFloat 的区别:
    StrToFloat 转换失败抛出 EConvertError 异常;
    StrToFloatDef 转换失败返回默认值;
    • TryStrToFloat 转换结果通过参数返回,函数返回值返回是否转换成功;
  • 没有 AFormatSettings 参数的 CurrToStrF 函数不是线程安全的,因为使用了全局变量 FormatSettings 作为默认的地区格式;带有 AFormatSettings 参数的函数是线程安全的。

例子:

void __fastcall TForm1::Button1Click(TObject *Sender)
{
    double val;
    if(TryStrToFloat(L"1234.56789",val)) // 当前地区 (中国)
        ShowFloat(val);
    else
        Memo1->Lines->Add(L"转换失败");

    TFormatSettings fs;
//  fs = TFormatSettings::Create(L"vi"); // 越南
    fs = TFormatSettings::Create(L"fr"); // 法国

    if(TryStrToFloat(L"1234.56789", val, fs)) // 法国和越南小数点必须用逗号 ','
        ShowFloat(val);
    else
        Memo1->Lines->Add(L"转换失败");

    if(TryStrToFloat(L"1234,56789", val, fs)) // 法国和越南小数点必须用逗号 ','
        ShowFloat(val);
    else
        Memo1->Lines->Add(L"转换失败");

    fs = TFormatSettings::Create(L"en_US");   // 美国
    if(TryStrToFloat(L"1234.56789", val, fs)) // 美国的小数点用小圆点和中国的一样 '.'
        ShowFloat(val);
    else
        Memo1->Lines->Add(L"转换失败");

    Sysutils::FormatSettings.DecimalSeparator = L','; // 把默认的小数点改成逗号 ','
    if(TryStrToFloat(L"1234,56789", val)) // 默认的小数点需要用逗号 ','
        ShowFloat(val);
    else
        Memo1->Lines->Add(L"转换失败");

    Sysutils::GetFormatSettings(); // 格式恢复默认值 - 当前地区 (中国) 的格式
    if(TryStrToFloat(L"1234.56789",val)) // 当前地区 (中国)
        ShowFloat(val);
    else
        Memo1->Lines->Add(L"转换失败");
}

运行结果:

运行结果

相关:


C++ Builder 参考手册System::SysutilsTryStrToFloat

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容