0

I am doing a rather large project (for me, is an AP JAVA course in high school). Anyways, for a portion of the project I need to be able to round a decimal and output it without the zero at the beginning before the decimal.

Ex: .4999 rounds ---> 0.5 I need: .4999 round ---> .5

Thanks in advance

user2864740
  • 60,010
  • 15
  • 145
  • 220
  • 4
    You must learn to distinguish a) a value of some type like double b) the human readable String describing this value. - Rounding is a mathematical operation and doesn't concern itself with "decimals" – Ingo Feb 19 '14 at 22:28
  • Yes, I understand this, I was just less clear and didn't explain every step. I round it is as a double then use Double.toString(a) to manipulate the string. – user3330235 Feb 19 '14 at 22:50

4 Answers4

3

As Ingo mentioned, you'll need to get a String representation of the number in order to modify the output as desired. One solution would be to use java.text.NumberFormat. setMinimumIntegerDigits(0) seems to fit the bill. I'm sure there are plenty more options as well.

  • 1+, I was not aware of `setMinimumIntegerDigits`. I've updated my working example to include [your answer](http://ideone.com/BhiplP). It is nice to know that there is a standard way to do it. – Anthony Accioly Feb 20 '14 at 00:47
3

Try this:

public static String format(double value, int decimalPlaces) {
   if (value >= 1 || value < 0) {
      throw new IllegalArgumentException("Value must be between 0 and 1");
   }
   final String tmp = String.format("%." + decimalPlaces + "f", value);
   return tmp.substring(tmp.indexOf('.'));
}

Examples:

System.out.println(format(0.4999d, 1)); // .5
System.out.println(format(0.0299d, 2)); // .03
System.out.println(format(0.34943d, 3)); // .349

Working Fiddle

Anthony Accioly
  • 21,918
  • 9
  • 70
  • 118
  • No problem, you can also replace `tmp.indexOf('.')` for `1`, I've kept it there because my original code was intended to extract decimal places from any positive number. Feel free to accept either mine or @briancherron answer which is also correct. – Anthony Accioly Feb 20 '14 at 00:33
0

The DecimalFormat class can be used.

DecimalFormat df = new DecimalFormat("####0.0");
System.out.println("Value: " + df.format(value));
Mark
  • 2,423
  • 4
  • 24
  • 40
  • 1
    DecimalFormat might be useful, but the format presented does not provide the OPs desired output: "I need: .4999 round ---> .5". – user2864740 Feb 19 '14 at 22:33
0

May seem weird to you, but you can use regex to strip off the leading zero like this:

(assuming that you already know how to round the decimal place to one)

        double value = 0.5;

        String val = Double.toString( value ).replaceAll( "^0(\\..*)$", "$1" );

        System.out.println( val );

Console:

       .5
Manoj Shrestha
  • 4,246
  • 5
  • 47
  • 67