Is it possible to cut decimal, and not round it. Like this.
decimal number = 12.159m;
How can I easily get 12.15 from number
and not 12.16?
Is there an easy way or is the string manipulation the only way?
Is it possible to cut decimal, and not round it. Like this.
decimal number = 12.159m;
How can I easily get 12.15 from number
and not 12.16?
Is there an easy way or is the string manipulation the only way?
You can do
Math.Floor(number * 100) / 100
Depending on how you want to handle (if you want to handle) negative numbers you could also use Truncate instead of Floor.
You can try this
decimal number = 12.159m;
number = Math.Truncate(number * 100m) / 100m;
Or another way of doing it, is to use a regex to capture the inputs and convert it back to decimal, for instance
Regex r = new Regex("(?<postNo>\d+)\.(?<preNo>\d{1,3})"); Decimal d= 12.159M; Match m = r.Match(d.ToString()); if (m.Success){ string s = string.Format("{0}.{1}", m.Groups["postNo"].Text, m.Groups["preNo"].Text); Decimal d = Decimal.Parse(s); }
In the 'preNo' tag in the regex, change it from \d{1,2} for example if you want to keep the digits BUT only two digits alone after the point. Ok, I know people will say, hey that's slow and downvote this answer...it serves to show there are ways to skin a cat!
Hope this helps, Best regards, Tom.
P.S: Have edited this as I realized after a downvote that the edit has escaped the literals that were missing!