Bogus
Bogus copied to clipboard
Decimal with X number of digits after decimal
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
- Is the feature something that currently cannot be done? It can but through a method name that makes the code read awkwardly. For example:
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.
- What alternatives have you considered?
Finance.Amount
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;
}
}
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
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?