简体   繁体   English

获取数字小数部分的最佳方法

[英]Best way to get the Fractional Part of a Number

Given const auto foo = 13.42 I would like to get the numbers fractional part, so .42 给定const auto foo = 13.42我想获取数字的小数部分,因此.42

I'm leaning toward just using fmod like: fmod(foo, 1.0) 我倾向于仅使用fmodfmod(foo, 1.0)

But I could also just do foo / static_cast<int>(foo) - 1.0 Or perhaps some other mystical method. 但是我也可以只做foo / static_cast<int>(foo) - 1.0或其他一些神秘的方法。

Would there be a motivation for me to not simply use fmod ? 我有动力不仅仅使用fmod吗?

Two ways I can think of, either a cast or rounding down with std::floor 我可以想到两种方式,无论是强制转换还是使用std::floor舍入

int main()
{    
    const auto foo = 13.53;

    auto firstWay = foo - static_cast<long long>(foo);  // Truncating via cast and subtracting

    auto otherWay = foo - std::floor(foo); // Rounding down and subtracting

    return 0;
}

Quick Bench Result shows the fmod approach as the slowest option by far, and the cast as the fastest: QuickBench 快速基准测试结果显示fmod方法是迄今为止最慢的选项,而强制转换则是最快的: QuickBench

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 带小数和小数部分的数字的正则表达式 - Regular expression for a number with fractional and decimal part c ++将数字的小数部分转换为整数 - c++ convert a fractional part of a number into integer 如何在转换为字符串时打印浮点数的小数部分 - How to print the fractional part of float number while converting to string 如何确定二进制数小数部分翻译的准确性? - How to determine the accuracy of the translation of the fractional part of a binary number? 从浮子中删除小数部分但保留类型的有效方法 - Efficient way to drop the fractional part from float but retain the type 浮点数的小数部分中以 10 为底的最大位数是多少 - What Are the Maximum Number of Base-10 Digits in the Fractional Part of a Floating Point Number fmod告诉我1的小数部分是1 - fmod telling me fractional part of 1 is 1 当双精度数的一个“小数部分”“溢出”时,最有效的方法是求和? - What is the most efficient way to sum a fractional part of a double and increment when it “overflows”? 用引号编写缓冲区的一部分的最佳方法是什么? - What is the best way to write a part of buffer with quoting? 使用6位设置浮点数的小数部分 - Set A Float's Fractional Part Using 6 Bits
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM