Replace numbers in string to numbers + "f"

132 Views Asked by At

I want to make tiny calculator that if you write for example 2/3 and you have got 0.6666667. I use DynamicExpresso.Core library but I need to write 2f/3f to have 0.6666667 (if I write 2/3 I get 0). I think I should use somethink like forCounting = Regex.Replace(forCounting, Regex.Match(forCounting, @"\d+").Value, Regex.Match(forCounting, @"\d+").Value + "f"); but it adds f after only first number. Do you have any ideas?

3

There are 3 best solutions below

0
On BEST ANSWER

Use

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string pattern = @"\d+(?:\.\d+)?";
        string substitution = "$0f";
        string input = "Text: 2/3, 1.9";
        string result = Regex.Replace(input, pattern, substitution);
        Console.WriteLine(result);
    }
}

See C# proof.

Results: Text: 2f/3f, 1.9f

1
On

Good code:

forCounting= Regex.Replace(forCounting, @"([0-9.]+)", @"$0f");
0
On

Starting with DynamicExpresso 2.6.0, it's possible to set a default numeric type.
For example, you can ask it to consider all numbers as double, and get the result you expect:

var target = new Interpreter();
target.SetDefaultNumberType(DefaultNumberType.Double);

var dbl = target.Eval<double>("2/3");
Console.WriteLine(dbl); // 0.6666666666666666