bchavez / Bogus

:card_index: A simple fake data generator for C#, F#, and VB.NET. Based on and ported from the famed faker.js.
Other
8.88k stars 507 forks source link

Decimal with X number of digits after decimal #332

Open xadvfh opened 4 years ago

xadvfh commented 4 years ago

Please describe why you are requesting a feature

I'm not sure if this is already provided but I couldn't find it. Is there a way to get a random decimal and specify the number of digits after the decimal? I can use the Finance.Amount option but amount seems weird to me.

Please answer any or all of the questions below

RuleFor(account=> account.InterestRate, f => f.Finance.Amount(min: 1, max: 5, decimals: 3)); I can wrap the method myself but was wondering if it makes sense to do that within Bogus.

Finance.Amount

bchavez commented 4 years ago

Hi @xadvfh,

I think, for now, you'd want to use a C# extension method workaround for readability as demonstrated below:

void Main()
{
   var account = new Faker<Account>()
      .RuleFor(a => a.InterestRate, f => f.Random.Decimal(1, 2, 4))
      .Generate();;

   account.Dump();
}

public static class ExtensionsForRandomizer
{
   public static decimal Decimal(this Randomizer r, decimal min = 0.0m, decimal max = 1.0m, int? decimals = null)
   {
      var value = r.Decimal(min, max);
      if( decimals.HasValue ){
         return Math.Round(value, decimals.Value);
      }
      return value;
   }
}

image


As far as getting a code change in Bogus; I could see int? decimals = null as an optional parameter for these precision types here:

https://github.com/bchavez/Bogus/blob/7caf7e0db504ac4a3796587f67a4e3b78c416c7c/Source/Bogus/Randomizer.cs#L170-L208

Your request kind of makes sense, but I'd have to think about it a little more and let it bake. I'm super careful when making changes to public APIs just because of the sheer amount of downloads involved. Once a change is deployed, it's hard to walk it back! But I'm leaning toward making the change.

Thank you for taking the time to make your issue known!

Thanks, Brian

RE: #319, #320

logiclrd commented 3 years ago

I mean, it could be added as a separate overload so that existing calls keep going to the same method they've been calling all along, right?