Search code examples
c#data-conversion

How do I shift the decimal point in C#


If I have an int equal to 8675309 what would be the best/quickest way to convert that into a float equal to 0.8675309f?

Examples:


input as an int: 8675309

output as a float: 0.8675309


input as an int: 4234512

output as a float: 0.4234512


input as an int: 56

output as a float: 0.56


input as an int: 123456

output as a float: 0.123456


input as an int: 654321

output as a float: 0.654321


The goal of this question is to create a decimal equivalent to a randomly generated integer as demonstrated above.

While those answering were trying to be helpful by attempting to assess what it would be used for to see if there would be a better/faster approach to the problem I was implementing this in, the entire point was to figure out the overall solution for myself and compare my results gained (using the accepted answer) to other known solutions for "evenly distributed" rng.

tldr; Not everyone wants the entire solution given to them up front. Sometimes answering exactly what is being asked for is the solution, even if the op needs something else down the line.

Edit: Everyone that was asking for more information couldn't see the individual tree for the forest, and my responses didn't progress the conversation in any significant amount other than to say "you're not answering my question, it couldn't be clearer what I'm asking" which wasn't helpful in the slightest. To clear up this question a bit, I've removed unnecessary clutter in the question, and clarified the goal of the original question.


Solution

  • The way you'd do this on paper is:

    1. Find the number of digits in 8675309
    2. Divide by 10^(number of digits)

    You can find the number of digits when written as base 10 either by formatting it as a string and counting the characters (bad), or by taking the log to the base 10 and rounding it up (good):

    int input = 8675309;
    int numDigits = (int)Math.Ceiling(Math.Log10(input));
    

    Then divide this by 10^numDigits:

    float result = input / MathF.Pow(10, numDigits);