microsoft/healthcare-shared-components
Publicmirrored from https://github.com/microsoft/healthcare-shared-componentsAvailable
src/Microsoft.Health.Core/Extensions/DecimalExtensions.cs
33lines · modecode
| 1 | // ------------------------------------------------------------------------------------------------- |
| 2 | // Copyright (c) Microsoft Corporation. All rights reserved. |
| 3 | // Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. |
| 4 | // ------------------------------------------------------------------------------------------------- |
| 5 | |
| 6 | using System; |
| 7 | |
| 8 | namespace Microsoft.Health.Core.Extensions; |
| 9 | |
| 10 | public static class DecimalExtensions |
| 11 | { |
| 12 | /// <summary> |
| 13 | /// Get a decimal for use as a precision modifier of 1/2 the next decimal point. |
| 14 | /// Given a value of 1 the decimal .5 is returned. Given a value of 100.00 the decimal .005 is returned. |
| 15 | /// </summary> |
| 16 | /// <param name="d">The decimal to modify.</param> |
| 17 | /// <returns>The value to modify the decimal by.</returns> |
| 18 | public static decimal GetPrescisionModifier(this decimal d) |
| 19 | { |
| 20 | // http://csharpindepth.com/Articles/General/Decimal.aspx |
| 21 | // Exponents are stored in the third byte of the fourth integer |
| 22 | var digitsBehindDecimal = BitConverter.GetBytes(decimal.GetBits(d)[3])[2]; |
| 23 | |
| 24 | // Exponents are limited to 28 decimal digits in most cases, so we can't modify the value further |
| 25 | if (digitsBehindDecimal >= 28) |
| 26 | { |
| 27 | return 0; |
| 28 | } |
| 29 | |
| 30 | // We want to create a decimal value that has the value of 5 one decimal digit further from 0 |
| 31 | return new decimal(5, 0, 0, false, (byte)(digitsBehindDecimal + 1)); |
| 32 | } |
| 33 | } |
| 34 | |