Thursday, June 5, 2014

Java: Rounding Number To Nearest Interval Such: 0.05, 0.5, 0.1, 5, 10, 100

RoundNumber.java


import java.math.BigDecimal;
import java.math.RoundingMode;
class RoundNumber {
    public static void main(String[] args) throws Exception {
         BigDecimal Price = new BigDecimal("232.573");
         BigDecimal Tick = new BigDecimal("0.05");
         BigDecimal Price2 = Price.divide(Tick, 9, RoundingMode.HALF_EVEN);
         Price2 = Price2.setScale(0, RoundingMode.HALF_UP).multiply(Tick);
         System.out.println("Price: " + Price + ", Round: " + Tick + ", Converted: " + Price2);
    }
}

Output:


Price: 232.573, Round: 0.05, Converted: 232.55
Price: 232.533, Round: 0.05, Converted: 232.55
Price: 232.523, Round: 0.05, Converted: 232.50
Price: 232.5235455, Round: 0.005, Converted: 232.525
Price: 232.5235, Round: 0.5, Converted: 232.5
Price: 232.446, Round: 0.5, Converted: 232.5
Price: 232.246, Round: 0.5, Converted: 232.0
Price: 1455.546, Round: 0.05, Converted: 1455.55
Price: 1455.528, Round: 0.05, Converted: 1455.55
Price: 1455.524, Round: 0.05, Converted: 1455.50
Price: 232.246, Round: 5, Converted: 230
Price: 232.546, Round: 5, Converted: 235
Price: 232.546, Round: 10, Converted: 230
Price: 235.546, Round: 10, Converted: 240
Price: 35.546, Round: 100, Converted: 0
Price: 55.546, Round: 100, Converted: 100
Price: 1455.524, Round: 100, Converted: 1500
Price: 1355.524, Round: 100, Converted: 1400
Price: 1248.524, Round: 100, Converted: 1200
Price: 1455.546, Round: 0.10, Converted: 1455.50
Price: 1455.556, Round: 0.10, Converted: 1455.60

External Link

No comments:

Post a Comment