简体   繁体   中英

Is there an C# equivalent of c++ fesetround() function?

I'm writting a C# library for interval arithmetic, and for that purpose I need to set floating-point operations rounding mode to Up and Down. I know that in C++ it can be achieved with a fesetround() function. Is there an equivalent in C#, or if there isn't, how can I achieve this the other way?

I followed Pascal Cuoq's advice and created a very simple - one function assembly. I post it in here if anyone else would ever experience such a problem.

Solution using my lib:

  1. Download dll file from: https://www.dropbox.com/s/o3vfxe4rpefhly7/RoundModeUtil.dll
  2. Add reference to the library in your project.
  3. Include using RoundModeUtils; line in project's code.
  4. Usage:

     static void RoundModeConfig::setround( int mode ); // mode can be set to one of the following values: static int RoundModeConfig::UPWARD static int RoundModeConfig::DOWNWARD static int RoundModeConfig::DEFAULT // To nearest mode. static int RoundModeConfig::TOWARDZERO

Thanks Hans Passant for your advice,i should keep it in mind. Thanks everybody for help, hope someone will find my dll useful :)

For windows:

/// <remarks>
/// https://en.cppreference.com/w/cpp/numeric/fenv/FE_round
/// </remarks>
public enum RoundMode
{
    /// <summary>
    /// Rounding towards nearest representable value.
    /// </summary>
    FE_TONEAREST = 0x00000000,

    /// <summary>
    /// Rounding towards negative infinity.
    /// </summary>
    FE_DOWNWARD = 0x00000100,

    /// <summary>
    /// Rounding towards positive infinity.
    /// </summary>
    FE_UPWARD = 0x00000200,

    /// <summary>
    /// Rounding towards zero.
    /// </summary>
    FE_TOWARDZERO = 0x00000300,
}


public static class ExternMethods
{
    [DllImport("ucrtbase.dll", EntryPoint = "fegetround", CallingConvention = CallingConvention.Cdecl)]
    public static extern RoundMode GetRound();

    [DllImport("ucrtbase.dll", EntryPoint = "fesetround", CallingConvention = CallingConvention.Cdecl)]
    public static extern int SetRound(RoundMode roundingMode);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM