-1

In my database, values are save in four digits after decimal (datatype = decimal(19,4)) and when I want to show it those values in the view I only show two digits after decimal. I used format string {0:F} to show only two digits after decimal. Now I have an issue when I have a values like 1.9988 it automatically round it to 2.00. How can I show exact values as in database just truncating last two digits?

Lakhae
  • 1,809
  • 5
  • 25
  • 40
  • possible duplicate of [Truncate Two decimal places without rounding](http://stackoverflow.com/questions/3143657/truncate-two-decimal-places-without-rounding) – David Jan 22 '15 at 19:57

2 Answers2

0

if you want 4 digits you need to tell it how many... use {0:F4}

This is an extension method I use for decimal values that allow me to truncate to a designated number of characters:

public static string TruncateToDecimalString( this decimal value , int numberOfDecimals )
{
    int power = (int)Math.Pow( 10 , numberOfDecimals );
    return ( Math.Truncate( value * power ) / power ).ToString( "F" + numberOfDecimals.ToString() );
}
Jared Peless
  • 1,120
  • 9
  • 11
  • I want to show only two digits for e.g `1.9998 to 1.99` – Lakhae Jan 22 '15 at 19:44
  • @Lakhae How about `{0:F2}`? – mason Jan 22 '15 at 19:46
  • For that, I don't know of a straight format block: but this does it as a method: public static string TruncateToDecimalString( this decimal value , int numberOfDecimals ) { int power = (int)Math.Pow( 10 , numberOfDecimals ); return ( Math.Truncate( value * power ) / power ).ToString( "F" + numberOfDecimals.ToString() ); } – Jared Peless Jan 22 '15 at 19:47
0
public static decimal TruncateDecimal(double value, int precision)
{
    decimal step = (decimal)Math.Pow(10, precision);
    int tmp = (int)Math.Truncate(step * (decimal)value);
    return tmp / step;
}

usage: decimal result = TruncateDecimal(123.4567, 2);

Example: https://dotnetfiddle.net/ZtazLn

Taken from here: Truncate Two decimal places without rounding

Community
  • 1
  • 1
  • why this answer received -1? – Konstantin Brodin Jan 22 '15 at 19:50
  • Answers should *contain* the answer, not just link to it. If either of those links ever goes away, the answer becomes useless. Including a DotNetFiddle is great, but the answer should include the code. Also, by linking to another question you've found a duplicate. So this question should be closed as a duplicate anyway. – David Jan 22 '15 at 19:57