简体   繁体   中英

Rounding Off decimal to two places

I have a decimal variable which contains values like 0.9 , 1.8 etc.Now ,i have to convert these values to like this 0.90 , 1.80. .Here is the code that i have tried to rounding off to two decimal places but it is giving me the same previous values only..

decimal Cost = noof * Rate;

Cost = Math.Round(Cost , 2);

Please help me ..

0.9 and 0.90 are the same value, you just want to display it differently.

You can use the following:

Cost.ToString("0.00")

Since the two numbers are exactly the same(data type and content), the only different between them are the way of displaying or the way of formatting numerical result.

You can format numeric results by using the String.Format method, or through the Console.Write or Console.WriteLine method, which calls String.Format . The format is specified by using format strings.

The link contains the supported standard format strings with description and examples.

在此处输入图片说明

And you can find more information related to formatting types there.

You can use the following,

double value = 0.9;
string formattedValue = value.ToString("N2");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM