Rounding is a common requirement in financial applications, with the Chinese financial habits encountering 0.5 of uniform upward rounding, but not in C # and Java as a default.
See C # code:
1 Static voidMain (string[] args)2 {3Decimal d =301353.05M;4Console.WriteLine (d);//301353.055Console.WriteLine (Math.Round (D,1));//301353.06Console.WriteLine (Math.Round (D,1, Midpointrounding.awayfromzero));//301353.17 8 Console.readkey ();9}
By default, if you want to discard the location, the exact value is 5, the system will see whether the previous one is odd or even, if it is even, discard the last 1 bits, that is, the above line 5, the output is 301353.0, which is not in line with the custom of the people, so we have to specify a 3rd parameter " Midpointrounding.awayfromzero "
A similar approach is proposed in Java, but there is a "flaw"
1 @Test2 Public voidTestscale () {3 DoubleD = 301353.05;4BigDecimal decimal =NewBigDecimal (d);5System.out.println (decimal);//301353.04999999998835846781730651855468756System.out.println (Decimal.setscale (1, roundingmode.half_up));//301353.07}
Similarly, when setting the precision, you can specify an additional parameter, Roundingmode. half_up, says that if the bit to discard is exactly 5, then the code looks fine, but the output value is 301353.0.
The reason is that bigdecimal inside the computer storage value is "301353.0499999999883584678173065185546875", that is, the 2nd decimal point is 4, the above code requires precision to 1 bits, so when the code executes, Just look at the 2nd decimal place, with a value of 4, not to the half standard, so throw it straight.
Improved method:
1 @Test2 Public voidTestscale () {3 DoubleD = 301353.05 + 0.0000000001;4BigDecimal decimal =NewBigDecimal (d);5System.out.println (decimal);//301353.05000000010477378964424133300781256System.out.println (Decimal.setscale (1, roundingmode.half_up));//301353.17}
In order to meet the financial accuracy of the premise, the number to be processed plus 1 small offset, so that the internal storage of the computer, the value becomes 301353.0500000001047737896442413330078125, so that the number 2nd bit into 5, Satisfies the condition of half_up.
Of course, this is expedient, if everyone has a better general method, welcome correction.
Nausea 0.5 Rounding problem