mirror of
https://github.com/microsoft/PowerToys.git
synced 2026-04-09 12:46:47 +02:00
[Run][Plugin] Rename Calculator plugin to follow the required schema (#9026)
This commit is contained in:
@@ -0,0 +1,82 @@
|
||||
// Copyright (c) Microsoft Corporation
|
||||
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using Mages.Core;
|
||||
|
||||
namespace Microsoft.PowerToys.Run.Plugin.Calculator
|
||||
{
|
||||
public class CalculateEngine
|
||||
{
|
||||
private readonly Engine _magesEngine = new Engine(new Configuration
|
||||
{
|
||||
Scope = new Dictionary<string, object>
|
||||
{
|
||||
{ "e", Math.E }, // e is not contained in the default mages engine
|
||||
},
|
||||
});
|
||||
|
||||
public const int RoundingDigits = 10;
|
||||
|
||||
public CalculateResult Interpret(string input)
|
||||
{
|
||||
// Using CurrentCulture this is user facing
|
||||
return Interpret(input, CultureInfo.CurrentCulture);
|
||||
}
|
||||
|
||||
public CalculateResult Interpret(string input, CultureInfo cultureInfo)
|
||||
{
|
||||
if (!CalculateHelper.InputValid(input))
|
||||
{
|
||||
return default;
|
||||
}
|
||||
|
||||
var result = _magesEngine.Interpret(input);
|
||||
|
||||
// This could happen for some incorrect queries, like pi(2)
|
||||
if (result == null)
|
||||
{
|
||||
return default;
|
||||
}
|
||||
|
||||
result = TransformResult(result);
|
||||
|
||||
if (string.IsNullOrEmpty(result?.ToString()))
|
||||
{
|
||||
return default;
|
||||
}
|
||||
|
||||
var decimalResult = Convert.ToDecimal(result, cultureInfo);
|
||||
var roundedResult = Round(decimalResult);
|
||||
|
||||
return new CalculateResult()
|
||||
{
|
||||
Result = decimalResult,
|
||||
RoundedResult = roundedResult,
|
||||
};
|
||||
}
|
||||
|
||||
public static decimal Round(decimal value)
|
||||
{
|
||||
return Math.Round(value, RoundingDigits, MidpointRounding.AwayFromZero);
|
||||
}
|
||||
|
||||
private static object TransformResult(object result)
|
||||
{
|
||||
if (result.ToString() == "NaN")
|
||||
{
|
||||
return Properties.Resources.wox_plugin_calculator_not_a_number;
|
||||
}
|
||||
|
||||
if (result is Function)
|
||||
{
|
||||
return Properties.Resources.wox_plugin_calculator_expression_not_complete;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user