Rounding a float number to a certain precision The Next CEO of Stack Overflowround() for float in C++What's the best way to do fixed-point math?How to round a number to n decimal places in JavaHow do I check if a string is a number (float)?How do I parse a string to a float or int in Python?Limiting floats to two decimal pointsIs floating point math broken?Difference between decimal, float and double in .NET?How to deal with floating point number precision in JavaScript?Formatting a number with exactly two decimals in JavaScriptFormat number to always show 2 decimal placesRound to at most 2 decimal places (only if necessary)

How do scammers retract money, while you can’t?

WOW air has ceased operation, can I get my tickets refunded?

Why is the US ranked as #45 in Press Freedom ratings, despite its extremely permissive free speech laws?

Is it my responsibility to learn a new technology in my own time my employer wants to implement?

What does "Its cash flow is deeply negative" mean?

Why don't programming languages automatically manage the synchronous/asynchronous problem?

How to count occurrences of text in a file?

Is it ever safe to open a suspicious html file (e.g. email attachment)?

What's the best way to handle refactoring a big file?

Between two walls

Why do we use the plural of movies in this phrase "We went to the movies last night."?

Why do airplanes bank sharply to the right after air-to-air refueling?

If a black hole is created from light, can this black hole then move at speed of light?

Make solar eclipses exceedingly rare, but still have new moons

Non-deterministic sum of floats

Why did we only see the N-1 starfighters in one film?

How to avoid supervisors with prejudiced views?

What benefits would be gained by using human laborers instead of drones in deep sea mining?

What expression will give age in years in QGIS?

How did people program for Consoles with multiple CPUs?

Is HostGator storing my password in plaintext?

Which tube will fit a -(700 x 25c) wheel?

Inappropriate reference requests from Journal reviewers

calculus parametric curve length



Rounding a float number to a certain precision



The Next CEO of Stack Overflowround() for float in C++What's the best way to do fixed-point math?How to round a number to n decimal places in JavaHow do I check if a string is a number (float)?How do I parse a string to a float or int in Python?Limiting floats to two decimal pointsIs floating point math broken?Difference between decimal, float and double in .NET?How to deal with floating point number precision in JavaScript?Formatting a number with exactly two decimals in JavaScriptFormat number to always show 2 decimal placesRound to at most 2 decimal places (only if necessary)










0















I want to round a float to maximum 4 decimals places. It mean 0.333333333 will be 0.3333, but 0.33 is still 0.33










share|improve this question



















  • 2





    Possible duplicate of round() for float in C++

    – quamrana
    Mar 8 at 13:40











  • Rounding as application logic, or rounding during conversion to string (to show in UI)? This two things are completely different issue!

    – Marek R
    Mar 8 at 13:54











  • Also what do you expect if input is: 33333.333 or 0.00000333333333.

    – Marek R
    Mar 8 at 14:01












  • Hmm let me give you some examples If input is 0.12346, output will be 0.1235 0.42 still be 0.42 0.523 still be 0.523

    – Tiến Trần
    Mar 8 at 14:17












  • Are you looking to round output, or looking to round the values in your variables? The first is sensible, but you seem to be asking for the second. The answers are different depending on which you want to do.

    – john
    Mar 8 at 14:50
















0















I want to round a float to maximum 4 decimals places. It mean 0.333333333 will be 0.3333, but 0.33 is still 0.33










share|improve this question



















  • 2





    Possible duplicate of round() for float in C++

    – quamrana
    Mar 8 at 13:40











  • Rounding as application logic, or rounding during conversion to string (to show in UI)? This two things are completely different issue!

    – Marek R
    Mar 8 at 13:54











  • Also what do you expect if input is: 33333.333 or 0.00000333333333.

    – Marek R
    Mar 8 at 14:01












  • Hmm let me give you some examples If input is 0.12346, output will be 0.1235 0.42 still be 0.42 0.523 still be 0.523

    – Tiến Trần
    Mar 8 at 14:17












  • Are you looking to round output, or looking to round the values in your variables? The first is sensible, but you seem to be asking for the second. The answers are different depending on which you want to do.

    – john
    Mar 8 at 14:50














0












0








0


0






I want to round a float to maximum 4 decimals places. It mean 0.333333333 will be 0.3333, but 0.33 is still 0.33










share|improve this question
















I want to round a float to maximum 4 decimals places. It mean 0.333333333 will be 0.3333, but 0.33 is still 0.33







c++ floating-point rounding precision






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 8 at 14:15









einpoklum

36.4k28132261




36.4k28132261










asked Mar 8 at 13:26









Tiến TrầnTiến Trần

1




1







  • 2





    Possible duplicate of round() for float in C++

    – quamrana
    Mar 8 at 13:40











  • Rounding as application logic, or rounding during conversion to string (to show in UI)? This two things are completely different issue!

    – Marek R
    Mar 8 at 13:54











  • Also what do you expect if input is: 33333.333 or 0.00000333333333.

    – Marek R
    Mar 8 at 14:01












  • Hmm let me give you some examples If input is 0.12346, output will be 0.1235 0.42 still be 0.42 0.523 still be 0.523

    – Tiến Trần
    Mar 8 at 14:17












  • Are you looking to round output, or looking to round the values in your variables? The first is sensible, but you seem to be asking for the second. The answers are different depending on which you want to do.

    – john
    Mar 8 at 14:50













  • 2





    Possible duplicate of round() for float in C++

    – quamrana
    Mar 8 at 13:40











  • Rounding as application logic, or rounding during conversion to string (to show in UI)? This two things are completely different issue!

    – Marek R
    Mar 8 at 13:54











  • Also what do you expect if input is: 33333.333 or 0.00000333333333.

    – Marek R
    Mar 8 at 14:01












  • Hmm let me give you some examples If input is 0.12346, output will be 0.1235 0.42 still be 0.42 0.523 still be 0.523

    – Tiến Trần
    Mar 8 at 14:17












  • Are you looking to round output, or looking to round the values in your variables? The first is sensible, but you seem to be asking for the second. The answers are different depending on which you want to do.

    – john
    Mar 8 at 14:50








2




2





Possible duplicate of round() for float in C++

– quamrana
Mar 8 at 13:40





Possible duplicate of round() for float in C++

– quamrana
Mar 8 at 13:40













Rounding as application logic, or rounding during conversion to string (to show in UI)? This two things are completely different issue!

– Marek R
Mar 8 at 13:54





Rounding as application logic, or rounding during conversion to string (to show in UI)? This two things are completely different issue!

– Marek R
Mar 8 at 13:54













Also what do you expect if input is: 33333.333 or 0.00000333333333.

– Marek R
Mar 8 at 14:01






Also what do you expect if input is: 33333.333 or 0.00000333333333.

– Marek R
Mar 8 at 14:01














Hmm let me give you some examples If input is 0.12346, output will be 0.1235 0.42 still be 0.42 0.523 still be 0.523

– Tiến Trần
Mar 8 at 14:17






Hmm let me give you some examples If input is 0.12346, output will be 0.1235 0.42 still be 0.42 0.523 still be 0.523

– Tiến Trần
Mar 8 at 14:17














Are you looking to round output, or looking to round the values in your variables? The first is sensible, but you seem to be asking for the second. The answers are different depending on which you want to do.

– john
Mar 8 at 14:50






Are you looking to round output, or looking to round the values in your variables? The first is sensible, but you seem to be asking for the second. The answers are different depending on which you want to do.

– john
Mar 8 at 14:50













4 Answers
4






active

oldest

votes


















2














Use the std::round() function



The C++ standard library offers functions for performing rounding. For floats, it is:



float round ( float arg );


this will round arg to the nearest integral value. Now, you want a different decimal resolution. So don't round your value, round your value times 10000, so your singles digit is now the former 0.0001 digit. Or more generally:



float my_round(
float x,
int num_decimal_precision_digits)

float power_of_10 = std::pow(10, num_decimal_precision_digits);
return std::round(x * power_of_10) / power_of_10;



Note that there may be accuracy issues, as floating-point computations and representations are only accurate to within a certain number of digits, and in my_round we have at least four sources of such inaccuracy: The power-of-10 calculation, the multiplication, the devision and the actual rounding.






share|improve this answer

























  • Is there another way doing that without using 'auto'? By the way thank you so much <3

    – Tiến Trần
    Mar 8 at 14:08











  • @TiếnTrần use double instead of auto, but I highly suggest you switch to at least c++11 and actually use auto.

    – Fureeish
    Mar 8 at 14:10











  • @TiếnTrần: You don't need the auto, you can use float. Or you can use doubles all over to reduce inaccuracies.

    – einpoklum
    Mar 8 at 14:12












  • strange that setprecision does rounding for output but there is no built in way to choose the number of digits for round

    – user463035818
    Mar 8 at 14:13











  • @user463035818: It's because round() comes from the C standard library, I guess. But you would have thought someone might have proposed that by now, yeah.

    – einpoklum
    Mar 8 at 14:14


















0














Here is a solution, for example:



float ret = float(round(0.333333333 * 10000)) / 10000)


You can write it as a function. Maybe there would be a better way?






share|improve this answer

























  • It truncates rather than rounds. I'd use round() instead.

    – HolyBlackCat
    Mar 8 at 13:45











  • @HolyBlackCat, yes, u r right. Thanks.

    – YaleCheung
    Mar 8 at 13:49











  • this will work for 0.33333333 but not for 3333.3333 or 0.00003333.

    – Marek R
    Mar 8 at 14:00


















0














Cast it into a fixed-point type



If you want to have your results rounded, with a fixed number of decimal digits, you're hinting that you don't really need the "floating" aspect of floating point numbers. Well, in this case, cast your value to a type which represents such numbers. Essentially, that would be a (run-time-variable) integer numerator and a compile-time-fixed denominator (which in your case would be 10,000).



There's an old question here on the site about doing fixed-point math:



What's the best way to do fixed-point math?



but I would suggest you consider the CNL library as something recent/popular. Also, several proposals have been made to add fixed-point types to the standard library. I don't know which one is the farthest advance, but have a look at this one: Fixed-Point Real Numbers by John McFarlane.



Back to your specific case: Fixed-point types can typically be constructed from floating-point ones. Just do that.






share|improve this answer
































    0














    Assuming you need print rounded number, this is one of a proper solutions:



    cout << setprecision(4) << x << 'n';


    std::setprecision documentation.



    Live demo



    Until more details are not provided it is impossible to provide a better answer.



    Please note if you are planing to round number x then print it, it will end with big headache, since some corner cases can produce much longer results then expected.






    share|improve this answer

























    • My impression is that you need to specify to used fixed precision, in order to be able to specify nr of digits after the decimal point. See cplusplus.com/reference/ios/ios_base/precision

      – Erik Alapää
      Mar 8 at 14:29











    • @ErikAlapää is correct. In order to get the desired behavior, std::fixed << std::setprecision(n) must be used. Otherwise, there will be n digits of total precision. Using std::fixed specifies n digits of decimal precision.

      – Richard
      Mar 8 at 14:32











    • @Richard Thank you for comment. I forgot to add that scientific notation also has same property as fixed, i.e. setting precision actually sets nr of digits after decimal point.

      – Erik Alapää
      Mar 8 at 14:52











    • @Richard where in question do you see detailed description of desired behavior? This is why I've wrote this is one of a proper solutions.

      – Marek R
      Mar 8 at 15:00












    • @MarekR Although it is ambiguous whether the original post intended to print or round to a value, I think the 'desired behavior' for rounding a floating point number to "4 decimals places" is to round the float to 4 decimal places. Using setprecision without std::fixed will truncate the decimal portion for numbers such as 1234.5678 (which gets printed as 1235 in your original answer).

      – Richard
      Mar 8 at 15:10












    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55064191%2frounding-a-float-number-to-a-certain-precision%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    4 Answers
    4






    active

    oldest

    votes








    4 Answers
    4






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2














    Use the std::round() function



    The C++ standard library offers functions for performing rounding. For floats, it is:



    float round ( float arg );


    this will round arg to the nearest integral value. Now, you want a different decimal resolution. So don't round your value, round your value times 10000, so your singles digit is now the former 0.0001 digit. Or more generally:



    float my_round(
    float x,
    int num_decimal_precision_digits)

    float power_of_10 = std::pow(10, num_decimal_precision_digits);
    return std::round(x * power_of_10) / power_of_10;



    Note that there may be accuracy issues, as floating-point computations and representations are only accurate to within a certain number of digits, and in my_round we have at least four sources of such inaccuracy: The power-of-10 calculation, the multiplication, the devision and the actual rounding.






    share|improve this answer

























    • Is there another way doing that without using 'auto'? By the way thank you so much <3

      – Tiến Trần
      Mar 8 at 14:08











    • @TiếnTrần use double instead of auto, but I highly suggest you switch to at least c++11 and actually use auto.

      – Fureeish
      Mar 8 at 14:10











    • @TiếnTrần: You don't need the auto, you can use float. Or you can use doubles all over to reduce inaccuracies.

      – einpoklum
      Mar 8 at 14:12












    • strange that setprecision does rounding for output but there is no built in way to choose the number of digits for round

      – user463035818
      Mar 8 at 14:13











    • @user463035818: It's because round() comes from the C standard library, I guess. But you would have thought someone might have proposed that by now, yeah.

      – einpoklum
      Mar 8 at 14:14















    2














    Use the std::round() function



    The C++ standard library offers functions for performing rounding. For floats, it is:



    float round ( float arg );


    this will round arg to the nearest integral value. Now, you want a different decimal resolution. So don't round your value, round your value times 10000, so your singles digit is now the former 0.0001 digit. Or more generally:



    float my_round(
    float x,
    int num_decimal_precision_digits)

    float power_of_10 = std::pow(10, num_decimal_precision_digits);
    return std::round(x * power_of_10) / power_of_10;



    Note that there may be accuracy issues, as floating-point computations and representations are only accurate to within a certain number of digits, and in my_round we have at least four sources of such inaccuracy: The power-of-10 calculation, the multiplication, the devision and the actual rounding.






    share|improve this answer

























    • Is there another way doing that without using 'auto'? By the way thank you so much <3

      – Tiến Trần
      Mar 8 at 14:08











    • @TiếnTrần use double instead of auto, but I highly suggest you switch to at least c++11 and actually use auto.

      – Fureeish
      Mar 8 at 14:10











    • @TiếnTrần: You don't need the auto, you can use float. Or you can use doubles all over to reduce inaccuracies.

      – einpoklum
      Mar 8 at 14:12












    • strange that setprecision does rounding for output but there is no built in way to choose the number of digits for round

      – user463035818
      Mar 8 at 14:13











    • @user463035818: It's because round() comes from the C standard library, I guess. But you would have thought someone might have proposed that by now, yeah.

      – einpoklum
      Mar 8 at 14:14













    2












    2








    2







    Use the std::round() function



    The C++ standard library offers functions for performing rounding. For floats, it is:



    float round ( float arg );


    this will round arg to the nearest integral value. Now, you want a different decimal resolution. So don't round your value, round your value times 10000, so your singles digit is now the former 0.0001 digit. Or more generally:



    float my_round(
    float x,
    int num_decimal_precision_digits)

    float power_of_10 = std::pow(10, num_decimal_precision_digits);
    return std::round(x * power_of_10) / power_of_10;



    Note that there may be accuracy issues, as floating-point computations and representations are only accurate to within a certain number of digits, and in my_round we have at least four sources of such inaccuracy: The power-of-10 calculation, the multiplication, the devision and the actual rounding.






    share|improve this answer















    Use the std::round() function



    The C++ standard library offers functions for performing rounding. For floats, it is:



    float round ( float arg );


    this will round arg to the nearest integral value. Now, you want a different decimal resolution. So don't round your value, round your value times 10000, so your singles digit is now the former 0.0001 digit. Or more generally:



    float my_round(
    float x,
    int num_decimal_precision_digits)

    float power_of_10 = std::pow(10, num_decimal_precision_digits);
    return std::round(x * power_of_10) / power_of_10;



    Note that there may be accuracy issues, as floating-point computations and representations are only accurate to within a certain number of digits, and in my_round we have at least four sources of such inaccuracy: The power-of-10 calculation, the multiplication, the devision and the actual rounding.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Mar 8 at 14:11

























    answered Mar 8 at 13:59









    einpoklumeinpoklum

    36.4k28132261




    36.4k28132261












    • Is there another way doing that without using 'auto'? By the way thank you so much <3

      – Tiến Trần
      Mar 8 at 14:08











    • @TiếnTrần use double instead of auto, but I highly suggest you switch to at least c++11 and actually use auto.

      – Fureeish
      Mar 8 at 14:10











    • @TiếnTrần: You don't need the auto, you can use float. Or you can use doubles all over to reduce inaccuracies.

      – einpoklum
      Mar 8 at 14:12












    • strange that setprecision does rounding for output but there is no built in way to choose the number of digits for round

      – user463035818
      Mar 8 at 14:13











    • @user463035818: It's because round() comes from the C standard library, I guess. But you would have thought someone might have proposed that by now, yeah.

      – einpoklum
      Mar 8 at 14:14

















    • Is there another way doing that without using 'auto'? By the way thank you so much <3

      – Tiến Trần
      Mar 8 at 14:08











    • @TiếnTrần use double instead of auto, but I highly suggest you switch to at least c++11 and actually use auto.

      – Fureeish
      Mar 8 at 14:10











    • @TiếnTrần: You don't need the auto, you can use float. Or you can use doubles all over to reduce inaccuracies.

      – einpoklum
      Mar 8 at 14:12












    • strange that setprecision does rounding for output but there is no built in way to choose the number of digits for round

      – user463035818
      Mar 8 at 14:13











    • @user463035818: It's because round() comes from the C standard library, I guess. But you would have thought someone might have proposed that by now, yeah.

      – einpoklum
      Mar 8 at 14:14
















    Is there another way doing that without using 'auto'? By the way thank you so much <3

    – Tiến Trần
    Mar 8 at 14:08





    Is there another way doing that without using 'auto'? By the way thank you so much <3

    – Tiến Trần
    Mar 8 at 14:08













    @TiếnTrần use double instead of auto, but I highly suggest you switch to at least c++11 and actually use auto.

    – Fureeish
    Mar 8 at 14:10





    @TiếnTrần use double instead of auto, but I highly suggest you switch to at least c++11 and actually use auto.

    – Fureeish
    Mar 8 at 14:10













    @TiếnTrần: You don't need the auto, you can use float. Or you can use doubles all over to reduce inaccuracies.

    – einpoklum
    Mar 8 at 14:12






    @TiếnTrần: You don't need the auto, you can use float. Or you can use doubles all over to reduce inaccuracies.

    – einpoklum
    Mar 8 at 14:12














    strange that setprecision does rounding for output but there is no built in way to choose the number of digits for round

    – user463035818
    Mar 8 at 14:13





    strange that setprecision does rounding for output but there is no built in way to choose the number of digits for round

    – user463035818
    Mar 8 at 14:13













    @user463035818: It's because round() comes from the C standard library, I guess. But you would have thought someone might have proposed that by now, yeah.

    – einpoklum
    Mar 8 at 14:14





    @user463035818: It's because round() comes from the C standard library, I guess. But you would have thought someone might have proposed that by now, yeah.

    – einpoklum
    Mar 8 at 14:14













    0














    Here is a solution, for example:



    float ret = float(round(0.333333333 * 10000)) / 10000)


    You can write it as a function. Maybe there would be a better way?






    share|improve this answer

























    • It truncates rather than rounds. I'd use round() instead.

      – HolyBlackCat
      Mar 8 at 13:45











    • @HolyBlackCat, yes, u r right. Thanks.

      – YaleCheung
      Mar 8 at 13:49











    • this will work for 0.33333333 but not for 3333.3333 or 0.00003333.

      – Marek R
      Mar 8 at 14:00















    0














    Here is a solution, for example:



    float ret = float(round(0.333333333 * 10000)) / 10000)


    You can write it as a function. Maybe there would be a better way?






    share|improve this answer

























    • It truncates rather than rounds. I'd use round() instead.

      – HolyBlackCat
      Mar 8 at 13:45











    • @HolyBlackCat, yes, u r right. Thanks.

      – YaleCheung
      Mar 8 at 13:49











    • this will work for 0.33333333 but not for 3333.3333 or 0.00003333.

      – Marek R
      Mar 8 at 14:00













    0












    0








    0







    Here is a solution, for example:



    float ret = float(round(0.333333333 * 10000)) / 10000)


    You can write it as a function. Maybe there would be a better way?






    share|improve this answer















    Here is a solution, for example:



    float ret = float(round(0.333333333 * 10000)) / 10000)


    You can write it as a function. Maybe there would be a better way?







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Mar 8 at 13:47

























    answered Mar 8 at 13:43









    YaleCheungYaleCheung

    56028




    56028












    • It truncates rather than rounds. I'd use round() instead.

      – HolyBlackCat
      Mar 8 at 13:45











    • @HolyBlackCat, yes, u r right. Thanks.

      – YaleCheung
      Mar 8 at 13:49











    • this will work for 0.33333333 but not for 3333.3333 or 0.00003333.

      – Marek R
      Mar 8 at 14:00

















    • It truncates rather than rounds. I'd use round() instead.

      – HolyBlackCat
      Mar 8 at 13:45











    • @HolyBlackCat, yes, u r right. Thanks.

      – YaleCheung
      Mar 8 at 13:49











    • this will work for 0.33333333 but not for 3333.3333 or 0.00003333.

      – Marek R
      Mar 8 at 14:00
















    It truncates rather than rounds. I'd use round() instead.

    – HolyBlackCat
    Mar 8 at 13:45





    It truncates rather than rounds. I'd use round() instead.

    – HolyBlackCat
    Mar 8 at 13:45













    @HolyBlackCat, yes, u r right. Thanks.

    – YaleCheung
    Mar 8 at 13:49





    @HolyBlackCat, yes, u r right. Thanks.

    – YaleCheung
    Mar 8 at 13:49













    this will work for 0.33333333 but not for 3333.3333 or 0.00003333.

    – Marek R
    Mar 8 at 14:00





    this will work for 0.33333333 but not for 3333.3333 or 0.00003333.

    – Marek R
    Mar 8 at 14:00











    0














    Cast it into a fixed-point type



    If you want to have your results rounded, with a fixed number of decimal digits, you're hinting that you don't really need the "floating" aspect of floating point numbers. Well, in this case, cast your value to a type which represents such numbers. Essentially, that would be a (run-time-variable) integer numerator and a compile-time-fixed denominator (which in your case would be 10,000).



    There's an old question here on the site about doing fixed-point math:



    What's the best way to do fixed-point math?



    but I would suggest you consider the CNL library as something recent/popular. Also, several proposals have been made to add fixed-point types to the standard library. I don't know which one is the farthest advance, but have a look at this one: Fixed-Point Real Numbers by John McFarlane.



    Back to your specific case: Fixed-point types can typically be constructed from floating-point ones. Just do that.






    share|improve this answer





























      0














      Cast it into a fixed-point type



      If you want to have your results rounded, with a fixed number of decimal digits, you're hinting that you don't really need the "floating" aspect of floating point numbers. Well, in this case, cast your value to a type which represents such numbers. Essentially, that would be a (run-time-variable) integer numerator and a compile-time-fixed denominator (which in your case would be 10,000).



      There's an old question here on the site about doing fixed-point math:



      What's the best way to do fixed-point math?



      but I would suggest you consider the CNL library as something recent/popular. Also, several proposals have been made to add fixed-point types to the standard library. I don't know which one is the farthest advance, but have a look at this one: Fixed-Point Real Numbers by John McFarlane.



      Back to your specific case: Fixed-point types can typically be constructed from floating-point ones. Just do that.






      share|improve this answer



























        0












        0








        0







        Cast it into a fixed-point type



        If you want to have your results rounded, with a fixed number of decimal digits, you're hinting that you don't really need the "floating" aspect of floating point numbers. Well, in this case, cast your value to a type which represents such numbers. Essentially, that would be a (run-time-variable) integer numerator and a compile-time-fixed denominator (which in your case would be 10,000).



        There's an old question here on the site about doing fixed-point math:



        What's the best way to do fixed-point math?



        but I would suggest you consider the CNL library as something recent/popular. Also, several proposals have been made to add fixed-point types to the standard library. I don't know which one is the farthest advance, but have a look at this one: Fixed-Point Real Numbers by John McFarlane.



        Back to your specific case: Fixed-point types can typically be constructed from floating-point ones. Just do that.






        share|improve this answer















        Cast it into a fixed-point type



        If you want to have your results rounded, with a fixed number of decimal digits, you're hinting that you don't really need the "floating" aspect of floating point numbers. Well, in this case, cast your value to a type which represents such numbers. Essentially, that would be a (run-time-variable) integer numerator and a compile-time-fixed denominator (which in your case would be 10,000).



        There's an old question here on the site about doing fixed-point math:



        What's the best way to do fixed-point math?



        but I would suggest you consider the CNL library as something recent/popular. Also, several proposals have been made to add fixed-point types to the standard library. I don't know which one is the farthest advance, but have a look at this one: Fixed-Point Real Numbers by John McFarlane.



        Back to your specific case: Fixed-point types can typically be constructed from floating-point ones. Just do that.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Mar 8 at 14:22

























        answered Mar 8 at 14:10









        einpoklumeinpoklum

        36.4k28132261




        36.4k28132261





















            0














            Assuming you need print rounded number, this is one of a proper solutions:



            cout << setprecision(4) << x << 'n';


            std::setprecision documentation.



            Live demo



            Until more details are not provided it is impossible to provide a better answer.



            Please note if you are planing to round number x then print it, it will end with big headache, since some corner cases can produce much longer results then expected.






            share|improve this answer

























            • My impression is that you need to specify to used fixed precision, in order to be able to specify nr of digits after the decimal point. See cplusplus.com/reference/ios/ios_base/precision

              – Erik Alapää
              Mar 8 at 14:29











            • @ErikAlapää is correct. In order to get the desired behavior, std::fixed << std::setprecision(n) must be used. Otherwise, there will be n digits of total precision. Using std::fixed specifies n digits of decimal precision.

              – Richard
              Mar 8 at 14:32











            • @Richard Thank you for comment. I forgot to add that scientific notation also has same property as fixed, i.e. setting precision actually sets nr of digits after decimal point.

              – Erik Alapää
              Mar 8 at 14:52











            • @Richard where in question do you see detailed description of desired behavior? This is why I've wrote this is one of a proper solutions.

              – Marek R
              Mar 8 at 15:00












            • @MarekR Although it is ambiguous whether the original post intended to print or round to a value, I think the 'desired behavior' for rounding a floating point number to "4 decimals places" is to round the float to 4 decimal places. Using setprecision without std::fixed will truncate the decimal portion for numbers such as 1234.5678 (which gets printed as 1235 in your original answer).

              – Richard
              Mar 8 at 15:10
















            0














            Assuming you need print rounded number, this is one of a proper solutions:



            cout << setprecision(4) << x << 'n';


            std::setprecision documentation.



            Live demo



            Until more details are not provided it is impossible to provide a better answer.



            Please note if you are planing to round number x then print it, it will end with big headache, since some corner cases can produce much longer results then expected.






            share|improve this answer

























            • My impression is that you need to specify to used fixed precision, in order to be able to specify nr of digits after the decimal point. See cplusplus.com/reference/ios/ios_base/precision

              – Erik Alapää
              Mar 8 at 14:29











            • @ErikAlapää is correct. In order to get the desired behavior, std::fixed << std::setprecision(n) must be used. Otherwise, there will be n digits of total precision. Using std::fixed specifies n digits of decimal precision.

              – Richard
              Mar 8 at 14:32











            • @Richard Thank you for comment. I forgot to add that scientific notation also has same property as fixed, i.e. setting precision actually sets nr of digits after decimal point.

              – Erik Alapää
              Mar 8 at 14:52











            • @Richard where in question do you see detailed description of desired behavior? This is why I've wrote this is one of a proper solutions.

              – Marek R
              Mar 8 at 15:00












            • @MarekR Although it is ambiguous whether the original post intended to print or round to a value, I think the 'desired behavior' for rounding a floating point number to "4 decimals places" is to round the float to 4 decimal places. Using setprecision without std::fixed will truncate the decimal portion for numbers such as 1234.5678 (which gets printed as 1235 in your original answer).

              – Richard
              Mar 8 at 15:10














            0












            0








            0







            Assuming you need print rounded number, this is one of a proper solutions:



            cout << setprecision(4) << x << 'n';


            std::setprecision documentation.



            Live demo



            Until more details are not provided it is impossible to provide a better answer.



            Please note if you are planing to round number x then print it, it will end with big headache, since some corner cases can produce much longer results then expected.






            share|improve this answer















            Assuming you need print rounded number, this is one of a proper solutions:



            cout << setprecision(4) << x << 'n';


            std::setprecision documentation.



            Live demo



            Until more details are not provided it is impossible to provide a better answer.



            Please note if you are planing to round number x then print it, it will end with big headache, since some corner cases can produce much longer results then expected.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Mar 8 at 15:05

























            answered Mar 8 at 14:10









            Marek RMarek R

            13.5k22776




            13.5k22776












            • My impression is that you need to specify to used fixed precision, in order to be able to specify nr of digits after the decimal point. See cplusplus.com/reference/ios/ios_base/precision

              – Erik Alapää
              Mar 8 at 14:29











            • @ErikAlapää is correct. In order to get the desired behavior, std::fixed << std::setprecision(n) must be used. Otherwise, there will be n digits of total precision. Using std::fixed specifies n digits of decimal precision.

              – Richard
              Mar 8 at 14:32











            • @Richard Thank you for comment. I forgot to add that scientific notation also has same property as fixed, i.e. setting precision actually sets nr of digits after decimal point.

              – Erik Alapää
              Mar 8 at 14:52











            • @Richard where in question do you see detailed description of desired behavior? This is why I've wrote this is one of a proper solutions.

              – Marek R
              Mar 8 at 15:00












            • @MarekR Although it is ambiguous whether the original post intended to print or round to a value, I think the 'desired behavior' for rounding a floating point number to "4 decimals places" is to round the float to 4 decimal places. Using setprecision without std::fixed will truncate the decimal portion for numbers such as 1234.5678 (which gets printed as 1235 in your original answer).

              – Richard
              Mar 8 at 15:10


















            • My impression is that you need to specify to used fixed precision, in order to be able to specify nr of digits after the decimal point. See cplusplus.com/reference/ios/ios_base/precision

              – Erik Alapää
              Mar 8 at 14:29











            • @ErikAlapää is correct. In order to get the desired behavior, std::fixed << std::setprecision(n) must be used. Otherwise, there will be n digits of total precision. Using std::fixed specifies n digits of decimal precision.

              – Richard
              Mar 8 at 14:32











            • @Richard Thank you for comment. I forgot to add that scientific notation also has same property as fixed, i.e. setting precision actually sets nr of digits after decimal point.

              – Erik Alapää
              Mar 8 at 14:52











            • @Richard where in question do you see detailed description of desired behavior? This is why I've wrote this is one of a proper solutions.

              – Marek R
              Mar 8 at 15:00












            • @MarekR Although it is ambiguous whether the original post intended to print or round to a value, I think the 'desired behavior' for rounding a floating point number to "4 decimals places" is to round the float to 4 decimal places. Using setprecision without std::fixed will truncate the decimal portion for numbers such as 1234.5678 (which gets printed as 1235 in your original answer).

              – Richard
              Mar 8 at 15:10

















            My impression is that you need to specify to used fixed precision, in order to be able to specify nr of digits after the decimal point. See cplusplus.com/reference/ios/ios_base/precision

            – Erik Alapää
            Mar 8 at 14:29





            My impression is that you need to specify to used fixed precision, in order to be able to specify nr of digits after the decimal point. See cplusplus.com/reference/ios/ios_base/precision

            – Erik Alapää
            Mar 8 at 14:29













            @ErikAlapää is correct. In order to get the desired behavior, std::fixed << std::setprecision(n) must be used. Otherwise, there will be n digits of total precision. Using std::fixed specifies n digits of decimal precision.

            – Richard
            Mar 8 at 14:32





            @ErikAlapää is correct. In order to get the desired behavior, std::fixed << std::setprecision(n) must be used. Otherwise, there will be n digits of total precision. Using std::fixed specifies n digits of decimal precision.

            – Richard
            Mar 8 at 14:32













            @Richard Thank you for comment. I forgot to add that scientific notation also has same property as fixed, i.e. setting precision actually sets nr of digits after decimal point.

            – Erik Alapää
            Mar 8 at 14:52





            @Richard Thank you for comment. I forgot to add that scientific notation also has same property as fixed, i.e. setting precision actually sets nr of digits after decimal point.

            – Erik Alapää
            Mar 8 at 14:52













            @Richard where in question do you see detailed description of desired behavior? This is why I've wrote this is one of a proper solutions.

            – Marek R
            Mar 8 at 15:00






            @Richard where in question do you see detailed description of desired behavior? This is why I've wrote this is one of a proper solutions.

            – Marek R
            Mar 8 at 15:00














            @MarekR Although it is ambiguous whether the original post intended to print or round to a value, I think the 'desired behavior' for rounding a floating point number to "4 decimals places" is to round the float to 4 decimal places. Using setprecision without std::fixed will truncate the decimal portion for numbers such as 1234.5678 (which gets printed as 1235 in your original answer).

            – Richard
            Mar 8 at 15:10






            @MarekR Although it is ambiguous whether the original post intended to print or round to a value, I think the 'desired behavior' for rounding a floating point number to "4 decimals places" is to round the float to 4 decimal places. Using setprecision without std::fixed will truncate the decimal portion for numbers such as 1234.5678 (which gets printed as 1235 in your original answer).

            – Richard
            Mar 8 at 15:10


















            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55064191%2frounding-a-float-number-to-a-certain-precision%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            How to get text form Clipboard with JavaScript in Firefox 56?How to validate an email address in JavaScript?How do JavaScript closures work?How do I remove a property from a JavaScript object?How do you get a timestamp in JavaScript?How do I copy to the clipboard in JavaScript?How do I include a JavaScript file in another JavaScript file?Get the current URL with JavaScript?How to replace all occurrences of a string in JavaScriptHow to check whether a string contains a substring in JavaScript?How do I remove a particular element from an array in JavaScript?

            Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme

            List of MPs elected to the English parliament in 1640 (April) Contents List of constituencies and members See also Notes References Navigation menueNational Archives – The Glynde Place ArchivesCobbett's Parliamentary history of England, from the Norman Conquest in 1066 to the year 1803'Aldermen in Parliament', The Aldermen of the City of London: Temp. Henry III – 1912onepage&q&f&#61, false 229