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)
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
|
show 3 more comments
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
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.333or0.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
|
show 3 more comments
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
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
c++ floating-point rounding precision
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.333or0.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
|
show 3 more comments
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.333or0.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
|
show 3 more comments
4 Answers
4
active
oldest
votes
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.
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 usedoubleinstead ofauto, but I highly suggest you switch to at leastc++11and actually useauto.
– Fureeish
Mar 8 at 14:10
@TiếnTrần: You don't need theauto, you can usefloat. Or you can usedoubles all over to reduce inaccuracies.
– einpoklum
Mar 8 at 14:12
strange thatsetprecisiondoes rounding for output but there is no built in way to choose the number of digits forround
– user463035818
Mar 8 at 14:13
@user463035818: It's becauseround()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
add a comment |
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?
It truncates rather than rounds. I'd useround()instead.
– HolyBlackCat
Mar 8 at 13:45
@HolyBlackCat, yes, u r right. Thanks.
– YaleCheung
Mar 8 at 13:49
this will work for0.33333333but not for3333.3333or0.00003333.
– Marek R
Mar 8 at 14:00
add a comment |
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.
add a comment |
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.
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 bendigits of total precision. Usingstd::fixedspecifiesndigits 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 wrotethis 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. Usingsetprecisionwithoutstd::fixedwill truncate the decimal portion for numbers such as1234.5678(which gets printed as1235in your original answer).
– Richard
Mar 8 at 15:10
add a comment |
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
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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.
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 usedoubleinstead ofauto, but I highly suggest you switch to at leastc++11and actually useauto.
– Fureeish
Mar 8 at 14:10
@TiếnTrần: You don't need theauto, you can usefloat. Or you can usedoubles all over to reduce inaccuracies.
– einpoklum
Mar 8 at 14:12
strange thatsetprecisiondoes rounding for output but there is no built in way to choose the number of digits forround
– user463035818
Mar 8 at 14:13
@user463035818: It's becauseround()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
add a comment |
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.
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 usedoubleinstead ofauto, but I highly suggest you switch to at leastc++11and actually useauto.
– Fureeish
Mar 8 at 14:10
@TiếnTrần: You don't need theauto, you can usefloat. Or you can usedoubles all over to reduce inaccuracies.
– einpoklum
Mar 8 at 14:12
strange thatsetprecisiondoes rounding for output but there is no built in way to choose the number of digits forround
– user463035818
Mar 8 at 14:13
@user463035818: It's becauseround()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
add a comment |
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.
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.
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 usedoubleinstead ofauto, but I highly suggest you switch to at leastc++11and actually useauto.
– Fureeish
Mar 8 at 14:10
@TiếnTrần: You don't need theauto, you can usefloat. Or you can usedoubles all over to reduce inaccuracies.
– einpoklum
Mar 8 at 14:12
strange thatsetprecisiondoes rounding for output but there is no built in way to choose the number of digits forround
– user463035818
Mar 8 at 14:13
@user463035818: It's becauseround()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
add a comment |
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 usedoubleinstead ofauto, but I highly suggest you switch to at leastc++11and actually useauto.
– Fureeish
Mar 8 at 14:10
@TiếnTrần: You don't need theauto, you can usefloat. Or you can usedoubles all over to reduce inaccuracies.
– einpoklum
Mar 8 at 14:12
strange thatsetprecisiondoes rounding for output but there is no built in way to choose the number of digits forround
– user463035818
Mar 8 at 14:13
@user463035818: It's becauseround()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
add a comment |
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?
It truncates rather than rounds. I'd useround()instead.
– HolyBlackCat
Mar 8 at 13:45
@HolyBlackCat, yes, u r right. Thanks.
– YaleCheung
Mar 8 at 13:49
this will work for0.33333333but not for3333.3333or0.00003333.
– Marek R
Mar 8 at 14:00
add a comment |
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?
It truncates rather than rounds. I'd useround()instead.
– HolyBlackCat
Mar 8 at 13:45
@HolyBlackCat, yes, u r right. Thanks.
– YaleCheung
Mar 8 at 13:49
this will work for0.33333333but not for3333.3333or0.00003333.
– Marek R
Mar 8 at 14:00
add a comment |
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?
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?
edited Mar 8 at 13:47
answered Mar 8 at 13:43
YaleCheungYaleCheung
56028
56028
It truncates rather than rounds. I'd useround()instead.
– HolyBlackCat
Mar 8 at 13:45
@HolyBlackCat, yes, u r right. Thanks.
– YaleCheung
Mar 8 at 13:49
this will work for0.33333333but not for3333.3333or0.00003333.
– Marek R
Mar 8 at 14:00
add a comment |
It truncates rather than rounds. I'd useround()instead.
– HolyBlackCat
Mar 8 at 13:45
@HolyBlackCat, yes, u r right. Thanks.
– YaleCheung
Mar 8 at 13:49
this will work for0.33333333but not for3333.3333or0.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
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
edited Mar 8 at 14:22
answered Mar 8 at 14:10
einpoklumeinpoklum
36.4k28132261
36.4k28132261
add a comment |
add a comment |
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.
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 bendigits of total precision. Usingstd::fixedspecifiesndigits 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 wrotethis 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. Usingsetprecisionwithoutstd::fixedwill truncate the decimal portion for numbers such as1234.5678(which gets printed as1235in your original answer).
– Richard
Mar 8 at 15:10
add a comment |
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.
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 bendigits of total precision. Usingstd::fixedspecifiesndigits 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 wrotethis 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. Usingsetprecisionwithoutstd::fixedwill truncate the decimal portion for numbers such as1234.5678(which gets printed as1235in your original answer).
– Richard
Mar 8 at 15:10
add a comment |
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.
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.
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 bendigits of total precision. Usingstd::fixedspecifiesndigits 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 wrotethis 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. Usingsetprecisionwithoutstd::fixedwill truncate the decimal portion for numbers such as1234.5678(which gets printed as1235in your original answer).
– Richard
Mar 8 at 15:10
add a comment |
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 bendigits of total precision. Usingstd::fixedspecifiesndigits 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 wrotethis 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. Usingsetprecisionwithoutstd::fixedwill truncate the decimal portion for numbers such as1234.5678(which gets printed as1235in 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
add a comment |
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
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.333or0.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