美文网首页
StrToFloat - C++ Builder

StrToFloat - C++ Builder

作者: 玄坴 | 来源:发表于2022-04-25 10:37 被阅读0次

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


    字符串转浮点数值

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

    System::Extended __fastcall StrToFloat(const System::UnicodeString S);
    System::Extended __fastcall StrToFloat(const System::UnicodeString S, const TFormatSettings &AFormatSettings);
    

    参数:

    • S:字符串;
    • AFormatSettings:地区格式;

    返回值:

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

    例:测试地区格式对 StrToFloat 的影响:包括全局变量 FormatSettings 和参数 AFormatSettings

    void TForm1::ShowFloat(double lfValue) // 显示浮点数,不使用地区格式
    {
        UnicodeString s;
        Memo1->Lines->Add(s.sprintf(L"%f",lfValue)); // 不使用地区格式
    }
    //---------------------------------------------------------------------------
    void __fastcall TForm1::Button1Click(TObject *Sender)
    {
        ShowFloat(StrToFloat(L"1234.56789")); // 当前地区 (中国)
    
        TFormatSettings fs;
    //  fs = TFormatSettings::Create(L"vi"); // 越南
        fs = TFormatSettings::Create(L"fr"); // 法国
        ShowFloat(StrToFloat(L"1234,56789", fs)); // 法国和越南小数点必须用逗号 ','
    
        fs = TFormatSettings::Create(L"en_US");   // 美国
        ShowFloat(StrToFloat(L"1234.56789", fs)); // 美国的小数点用小圆点和中国的一样 '.'
    
        Sysutils::FormatSettings.DecimalSeparator = L','; // 把默认的小数点改成逗号 ','
        ShowFloat(StrToFloat(L"1234,56789")); // 默认的小数点需要用逗号 ','
    
        Sysutils::GetFormatSettings(); // 格式恢复默认值 - 当前地区 (中国) 的格式
        ShowFloat(StrToFloat(L"1234.56789")); // 当前地区 (中国)
    }
    

    运行结果:

    运行结果

    相关:


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

    相关文章

      网友评论

          本文标题:StrToFloat - C++ Builder

          本文链接:https://www.haomeiwen.com/subject/pkidahtx.html