szpic
szpic

Reputation: 4498

How to add zeros after decimal point

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

Upvotes: 8

Views: 16902

Answers (1)

Luaan
Luaan

Reputation: 63772

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").

Upvotes: 19

Related Questions