Skip to content

Math.Round(double,int,MidpointRounding) Math.Round(decimal,int,MidpointRounding) different result #71192

@erikzhouxin

Description

@erikzhouxin

Description

            // 单精度浮点数(Float)
            Console.WriteLine(Math.Round(18.254550f, 4, MidpointRounding.ToEven)); // 18.2546
            Console.WriteLine(Math.Round(18.745450f, 4, MidpointRounding.ToEven)); // 18.7454
            // 双精度浮点数(Double)
            Console.WriteLine(Math.Round(18.254550d, 4, MidpointRounding.ToEven)); // 18.2545
            Console.WriteLine(Math.Round(18.745450d, 4, MidpointRounding.ToEven)); // 18.7455
            // 高精度浮点数(Decimal)
            Console.WriteLine(Math.Round(18.254550m, 4, MidpointRounding.ToEven)); // 18.2546
            Console.WriteLine(Math.Round(18.745450m, 4, MidpointRounding.ToEven)); // 18.7454

            Console.WriteLine(string.Format("{0:f4}", 18.254550d));
            Console.WriteLine(string.Format("{0:f4}", 18.745450d));

Why this is different result?

in fact string.Format("{0:f4}", double) not consistent with Math.Round Method

Reproduction Steps

Math.Round(double,int,MidpointRounding)
Math.Round(decimal,int,MidpointRounding)

Expected behavior

Math.Round(double,int,MidpointRounding)
Math.Round(decimal,int,MidpointRounding)
by useful digit precision these can return the same number,and string.format use math.round default MidpointRounding

Actual behavior

Math.Round(double,int,MidpointRounding)
Math.Round(decimal,int,MidpointRounding)
// 18.254550 and 18.745450 is different

Regression?

netcoreapp3.1 or net6.0

Known Workarounds

No response

Configuration

No response

Other information

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions