Java Number Round round(String num, int length)

Here you can find the source of round(String num, int length)

Description

round

License

Apache License

Declaration

private static String round(String num, int length) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {
    private static String round(String num, int length) {
        // Helper function for realToString.
        // Round off num to the given field width
        if (num.indexOf('.') < 0)
            return num;
        if (num.length() <= length)
            return num;
        if (num.charAt(length) >= '5' && num.charAt(length) != '.') {
            char[] temp = new char[length + 1];
            int ct = length;
            boolean rounding = true;
            for (int i = length - 1; i >= 0; i--) {
                temp[ct] = num.charAt(i);
                if (rounding && temp[ct] != '.') {
                    if (temp[ct] < '9') {
                        temp[ct]++;// w  w  w  .  ja  va 2  s . c o  m
                        rounding = false;
                    } else
                        temp[ct] = '0';
                }
                ct--;
            }
            if (rounding) {
                temp[ct] = '1';
                ct--;
            }
            // ct is -1 or 0
            return new String(temp, ct + 1, length - ct);
        } else
            return num.substring(0, length);
    }
}

Related

  1. round(int top, int div2, int divisor)
  2. round(int x, int quantum)
  3. round(Integer a)
  4. round(Number number, Number unit)
  5. Round(Object in)
  6. round4(int n)
  7. round_pow2(int x)
  8. round_up(int value, int multiple)
  9. roundAdd(double a, double b)