简体   繁体   中英

How can I return only two decimals when multiplying numbers?

I have to multiply two decimal numbers: 6,0 * 5,50 which results in: 33,000

How can I cut the last 0 off the result? I want to have 33,00 as the result.

To multiply, I use the query:

var rr = (from s in baza.customer
          where userID == s.userID
          && s.data.Month == dat
          select s.hours * s.prise.Sum();

You have a character-set problem. Your code is running in a North American locale, where , is a thousands separator (and . is the decimal marker).

As it seems there's some confusion here, I'll post a similar answer to two others, but with a short but complete program to show why it's necessary.

Firstly, it's worth clarifying that (as seen in comments) this is multiplying together two numbers less than 10 - as C# literals, they'd be 6.0m and 5.50m. The fact that they're decimal values is also highly relevant - as decimal maintains trailing zeroes, whereas double doesn't. So:

// Note: my system is in en-gb
using System;

class Test
{
    static void Main()
    {
        decimal x = 6.0m;
        decimal y = 5.50m;
        decimal z = x * y;
        Console.WriteLine(z); // Prints 33.000
        Console.WriteLine(z.ToString("0.00")); // Prints 33.00
        // Same with composite formatting
        Console.WriteLine("{0:0.00}", z); // Still prints 33.00
        // If you want fewer than 2 decimal digits when they're
        // not necessary
        Console.WriteLine(z.ToString("0.##")); // Prints 33
    }
}

If the current thread's culture uses ',' instead of '.' as a decimal separator then obviously you'll get "33,00" instead.

If you want to round the actual value to 2 decimal places, you can do that with decimal.Round :

decimal rounded = decimal.Round(z, 2);

but of course this could lose significant information.

Note that you should usually only be applying string formatting when you're going to present the information to the user.

尝试使用字符串格式设置: string.Format("{0:0.##}", number)

Why don't you format the value at the time of output rather than try to cut decimals an the time of calculation?

Use

String.Format("{0:0.##}", number) 

or

String.Format("{0:0.00}", number)

to have only to decimals in your output.

NumberFormat nf4 = new DecimalFormat("0000");
var rr=+nf6.format(new Integer(rr));

Assuming you want the representation in string form, you need to format the result using the Standard Numeric Format Strings . For example, after a quick test on the value you posted (33.000), the code (33.000).ToString("f") gave a result of 33.00.

Note: "f" may not be the actual format specifier you require - it would be best reading through the article I've linked first.

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