使用Math.Round进行舍入

本文关键字:舍入 Round Math 使用 | 更新日期: 2023-09-27 18:00:26

我想知道是否有办法使用Math.Round函数将0.05美分的值转换为5美分?我知道我只需将值乘以100就可以做到这一点,但我不想这样做,因为值存储在一个数组中,在执行其他函数时会破坏我的其他计算。

例如,如果值小于1美元,那么我想打印出没有小数的分值,请参考下面的代码:

double[] coins = {0.05,0.10,0.20,0.50,1.00,2.00};
Console.WriteLine("Change is as follows:");
        for (int j = 0; j < change_given.Length; j++)
        {
            if (change_given[j] == 0)
            {
                continue;
            }
            if (coins[j] < 1)
            {
                Console.WriteLine("{0} x {1}c", change_given[j], coins[j]);
            }
            else
            {
                Console.WriteLine("{0} x ${1}", change_given[j], coins[j]);
            }
        }

使用Math.Round进行舍入

看起来这只是为了显示目的。如果你乘以coins[j]*100,你就不会更新硬币[j]:

    for (int j = 0; j < change_given.Length; j++)
    {
        if (change_given[j] == 0)            
            continue;            
        if (coins[j] < 1)
            Console.WriteLine("{0} x {1}c", change_given[j], coins[j]*100);
        else
            Console.WriteLine("{0} x ${1}", change_given[j], coins[j]);
    }

目标:以整数打印美元美分。源是一个替身数组。不需要更改原始数组本身,只需出于显示目的读取其成员即可。

观看现场演示。

预期输出

Change is as follows:
5 cents
10 cents
20 cents
50 cents
1 dollar
1 dollar and 42 cents
2 dollars

代码

using System;
public class Test
{
    public static void Main()
    {
        double[] coins = {0.05,0.10,0.20,0.50,1.00,1.42,2.00};
        Console.WriteLine("Change is as follows:");
        for (int j = 0; j < coins.Length; j++)
        {
            var amount = coins[j];
            var dollars = Math.Floor(amount);
            var change = amount - dollars;
            var cents = 100*change;
            string ds = dollars == 1 ? String.Empty : "s";
            string cs = cents == 1 ? String.Empty : "s";
            if (amount >= 0 && amount < 1)
            {
                Console.WriteLine("{0} cents", cents);
            }
            else if (dollars >= 1 && cents == 0)
            {
                Console.WriteLine("{0} dollar{1}", dollars, ds);
            }
            else
            {
                Console.WriteLine("{0} dollar{1} and {2} cent{3}",
                    dollars, ds, cents, cs);
            }
        }
    }
}