I know that convert int to double in C++ has many ways. but what is the best way for do this?
Asked
Active
Viewed 534 times
-2
-
Where do you need it? What is the context. **What do you mean by "best"?** – Jason Aug 15 '22 at 12:34
-
1Refer to [how to ask](https://stackoverflow.com/help/how-to-ask) where the first step is to *"search and then research"* and you'll find plenty of related SO questions. Also, it is not clear what you mean by "best". – Jason Aug 15 '22 at 12:38
-
2Sheesh. All this `static_cast` stuff in the answers and in the linked questions. You don't need a cast to tell the compiler to do something it would do anyway. `int x = 3; double d = x;` is all you need. Yes, some compilers might warn you about that, and if you have some non-standard setting to pretend that every warning is actually something important, it might refuse to compile it. But that's how you do it. Don't obfuscate your code with unnecessary casts. – Pete Becker Aug 15 '22 at 13:57
-
Of course, your option is also valid, but it is completely up to the developer either to use implicit conversion or explicit casting. The first option, as all implicit solutions, hides some logic, may be unintuitive and difficult to fix, when program will start to fire errors. The second option, as you pointed out, is technically unnecessary and just adds some more code, but it tells every developer that some type is being casted to another (which may be not so obvious in implicit conversion, if developer sees only `double d = x;`). – Akmal-threepointsix Aug 15 '22 at 14:19
2 Answers
2
Use static_cast<double>(expression).
In general, it is recommended to use C++ ways of casting (static_cast
, dynamic_cast
), instead of the old C-style casting, such as (double)int
, (int)double
.

Akmal-threepointsix
- 84
- 7
1
A simple static_cast
double d = static_cast<double>(value); // where value is your int

Cory Kramer
- 114,268
- 16
- 167
- 218
-
`double d = value;` will also work, without the cast. My druthers is that the cast was necessary... alas, but for the sake of "C legacy backwards compatibility". – Eljay Aug 15 '22 at 14:11