Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add zeros after decimal point

Tags:

c#

decimal

Lets assume that I have decimal like this:

decimal a= 12.1

But I want it to be :

a=12.10

is it possible to make it without using .toString()? I tried using decimal.Round() but this still sets a=12.1

Clarification: the data eg. 12.1 is received from webservice so I can not simple change it to the 12.10M

like image 436
szpic Avatar asked Dec 08 '22 02:12

szpic


1 Answers

Actually, .NET's decimal type does include zeroes after decimal point. You just have to use a decimal literal:

var a = 12.10M;

If you need this for real-time values rather than compile-time, you can multiply with another decimal literal, for example:

var a = someDecimalInput;
return a * 1.0000M; // Ensures at least four digits after the decimal point.

However, I'd still advise against this - formatting is better left to the presentation layer, and that's where you want to handle how many decimal points to display. You'd usually use something like a.ToString("f2").

like image 189
Luaan Avatar answered Dec 28 '22 13:12

Luaan