package nomadgui.tools;

/** Provides various static methods for the formatting of numbers. */

public class Format {
  private Format() {}           // defeat instantiation

  /** Rounds a double to to the specified number of places.  The number is
    * simply truncated at the specified number of decimal places.  For example,
    * the following code:
    * <pre>
    * double x = 5.374965;
    * System.out.println(Format.round(x, 2));
    * </pre>
    * Will print "5.37" to the screen.
    * 
    * @param d The double value to be rounded.
    * @param place The number of places to round the value to.
    * @return The value of the double truncated at the specified
    *         number of places.
    */
  
  public static double round(double d, int place) {
    if (d==0) return d;

    place = (int)Math.pow(10,place);
    
    if (d<0) {
      d *= place;        // multiply by 10^place (shift decimal by <place>)
      d = Math.ceil(d);  // truncate decimal
      d /= place;        // divide by 10^place (shift decimal back)
    }

    if (d>0) {
      d *= place;        // multiply by 10^place (shift decimal by <place>)
      d = Math.floor(d); // truncate decimal
      d /= place;        // divide by 10^place (shift decimal back)
    }

    return d;
  }

  /** Rounds a float to to the specified number of places.  The number is
    * simply truncated at the specified number of decimal places.  For example,
    * the following code:
    * <pre>
    * float x = 5.374965;
    * System.out.println(Format.round(x, 2));
    * </pre>
    * Will print "5.37" to the screen.
    * 
    * @param d The float value to be rounded.
    * @param place The number of places to round the value to.
    * @return The value of the float truncated at the specified
    *         number of places.
    */
  
  public static float round(float d, int place) {
    if (d==0) return d;

    place = (int)Math.pow(10,place);
    
    if (d<0) {
      d *= place;        // multiply by 10^place (shift decimal by <place>)
      d = (float)Math.ceil(d);  // truncate decimal
      d /= place;        // divide by 10^place (shift decimal back)
    }

    if (d>0) {
      d *= place;        // multiply by 10^place (shift decimal by <place>)
      d = (float)Math.floor(d); // truncate decimal
      d /= place;        // divide by 10^place (shift decimal back)
    }

    return d;
  }
}
