【问题标题】:How to set DecimalSeparator for a float in C++ Builder如何在 C++ Builder 中为浮点数设置 DecimalSeparator
【发布时间】:2021-03-13 23:36:15
【问题描述】:

我使用的是 C++ Builder,并且我的语言环境是欧洲的,所以我有一个逗号作为小数分隔符。

我需要将双精度值转换为小数点值,并使用点作为分隔符。

我在任何地方都找不到答案。

【问题讨论】:

    标签: c++builder


    【解决方案1】:

    DecimalSeparator是一个全局变量,只需在格式化double之前将其设置为所需的字符,例如:

    #include <SysUtils.hpp>
    
    System::String FormatWithDot(double value)
    {
        System::Char old = Sysutils::DecimalSeparator;
        Sysutils::DecimalSeparator = _D('.');
        System::String s = Sysutils::FloatToStr(value);
        Sysutils::DecimalSeparator = old;
        return s;
    }
    
    System::String s = FormatWithDot(123.45);
    

    或者,如果您需要在多个线程中执行此操作,请使用线程安全版本,TFormatSettings::DecimalSeparator

    #include <SysUtils.hpp>
    
    System::String FormatWithDot(double value)
    {
        Sysutils::TFormatSettings fmt = Sysutils::TFormatSettings::Create();
        fmt.DecimalSeparator = _D('.');
        return Sysutils::FloatToStr(value, fmt);
    }
    
    System::String s = FormatWithDot(123.45);
    

    请注意,DecimalSeparator 仅适用于基于 Delphi 的 RTL 函数,如 FloatToStr()Format() 等。它不适用于基于 C++ 的函数,如 std::(s)printf()std::to_string()std::ostream::operator&lt;&lt;、等等。对于那些,您需要使用 C++ 语言环境。

    【讨论】:

    • 非常感谢您的努力。我通过将 fmt 传递给 FloatToStr 自己解决了这个问题。
    【解决方案2】:

    我自己在凌晨解决了这个问题。您可以使用:

    TFormatSettings fmt = TFormatSettings::Create();
    fmt.DecimalSeparator = '.';
    

    然后像这样格式化一个双精度:

    FloatToStr(price, fmt);
    

    我希望它对某人有所帮助。我快疯了。

    【讨论】:

      【解决方案3】:

      我知道这是一个非常古老的线程,但我今天遇到了这个问题。就我而言,我的解决方案是这样的:

      String DotFormatted(long double value, int numberOfDecimals=2) {
          String result = Format("%." + IntToStr(numberOfDecimals) + "f", ARRAYOFCONST((value)));
          result = StringReplace( result, ",", ".", TReplaceFlags() << rfReplaceAll);     
          return result; 
      }
      

      这相当于我用另一种语言编写的另一个。对我来说,它很有用,因为 numberOfDecimals 参数。

      【讨论】:

        猜你喜欢
        • 2022-01-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-03
        • 1970-01-01
        • 2022-01-10
        • 1970-01-01
        • 2019-02-06
        相关资源
        最近更新 更多