2

Is there any way in C# to treat all numeric literals (which I describe as "magic numbers") as doubles?

For example

double number = 1;
var a = 7 / 8 * number;

In this calculation 7 / 8 returns 0, but 7.0 / 8.0 returns 0.875.

In my case most of these formulas are copied from VBA and they are all over the place. It would be very time consuming and error prone to find all of them and replace them manually.

Peter Duniho
  • 68,759
  • 7
  • 102
  • 136
Adam
  • 1,825
  • 1
  • 17
  • 24
  • Excuse me, but what do you need to do? Match integer numbers? – Wiktor Stribiżew Feb 27 '17 at 16:58
  • IMO these are two different questions, 1) can the default data type of numeric literals be "overridden" and 2) can I do a specific pattern search and replace in my IDE? – Cee McSharpface Feb 27 '17 at 16:59
  • You're right, I'll take out the second part – Adam Feb 27 '17 at 17:05
  • @bassfader that is in the question. But it would be nice to treat all magic numbers as doubles because most of them are copied and pasted from VBA and it will be very time consuming to replace them all. – Adam Feb 27 '17 at 17:11
  • There are way too many ways to approach this. For one, you could use the built-in regex-based search-and-replace to find all numeric literals and just append `.0` to them. Then go fix by hand any compile-time errors caused by inappropriate application. Personally though, I think you _should_ have to go through and replace them manually, because you shouldn't have these hard-coded numeric literals in the code in the first place. They should have proper names, and this is a great time to go fix that deficiency in the code. Just fix the code so you have `const double ratio = 7d / 8;`, etc. – Peter Duniho Feb 27 '17 at 17:21
  • @Adam "copied and pasted from VBA"? if you manually converted the rest of the code, the overhead for writing 1d instead of 1 should be negligible. if you used an automatic conversion, can it be tweaked maybe? how many LOC are we talking about? – Cee McSharpface Feb 27 '17 at 17:35
  • You're right it was not too many lines, ended up using the solution posted here http://stackoverflow.com/questions/42491695/visual-studio-replace-magic-number-integers-with-doubles?noredirect=1#comment72123270_42491695 – Adam Feb 27 '17 at 17:43

1 Answers1

0

There is no global setting, code must be updated. The method I used is posted in the answer of this question.

Visual Studio replace magic number integers with doubles

Community
  • 1
  • 1
Adam
  • 1,825
  • 1
  • 17
  • 24