CSharp examples for System:Math Number
takes a decimal value, and truncates all the decimals after the total Decimal specified.
/* ******************************************************************************* * Copyright (c) 2005-2012 Zibler S de RL MI. * /*from w w w . jav a 2 s . c o m*/ * This file is part of Zibler. * * Zibler is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Zibler is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Zibler. If not, see <http://www.gnu.org/licenses/>. * * *******************************************************************************/ using System.Threading; using System.Text; using System.Security.Cryptography; using System; public class Main{ /// <summary> /// This function takes a decimal value, and truncates all the decimals /// after the totalDecimal specified. So if totalDecimal is 2, then /// all decimals after the second decimal of number will be truncated. /// all decimals after the second decimal of number will be truncated. /// </summary> /// <param name="number">Number to truncate</param> /// <param name="totalDecimal">Total decimals to truncate</param> /// <returns></returns> public static decimal TruncateDecimalPlaces (decimal number, int totalDecimal) { int decBase = 10; if (totalDecimal > 10) return 0.0m; int multiplier = decBase * totalDecimal; /* Get the integer part of the decimal */ decimal intPortion = Decimal.Truncate (number); /* Get only the decimal part */ decimal decimalPortion = number - intPortion; /* Multiply the decimal portion to the multiplier to create * an integer number equivalent to the decimals we want to keep */ decimal decToKeep = decimalPortion * multiplier; /* Truncate to keep only the integer part */ decToKeep = Decimal.Truncate (decToKeep); /* Divide the integer part of the decimals to keep by * the multiplier, to convert back to decimals */ if (multiplier > 0) decToKeep = decToKeep / multiplier; else decToKeep = 0; /* Add the integer portion of the original value to the * decimals to keep to generate a result */ decimal result = intPortion + decToKeep; return result; } }