• Post Reply Bookmark Topic Watch Topic
  • New Topic

Needing help in java with string.format for mathematical functions - floor, round and ceil  RSS feed

 
Conran Pearce
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi guys, I am currently struggling to use String.format() to round numbers - using ceil, floor and round on double variables.

Been given the code below to work from but cannot understand or find online where to go from there:

    double a = 17.123;
    String x = String.format("a = %1$.2f",x);
    System.out.println(x);

Anyone with any advice would be great!
 
Carey Brown
Saloon Keeper
Posts: 3328
46
Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ceil and floor are not a part of String.format(). You can use String.format() to format a double after applying Math.ceil() to it, as in
Or
 
Campbell Ritchie
Marshal
Posts: 56570
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

Have you been through the Java™ Tutorials? Look that section, also this one. Those links use print, but don't worry; the format Strings for String#format look exactly the same.
Decide what format you want floor/ceil printed in. How many places do you want before the decimal point, and how many after? If you use %f for fixed point, add those two figures and add one. That gives the you number to the left, and the number to the right is places after the decimal point. So %6.2f gives three places before the decimal point, one place for the decimal point and two after. If you omit the left number, you get as many places before the decimal point as the runtime thinks you need.
You only need 1$ when you have already passed the first argument and you want to reuse it, so you can remove that.
The argument to the right of ", is the double you want to print, not the name of the String, so try a instead.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!