• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to format the number  RSS feed

 
gayathri ramesh
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I am getting 45.789887 as input from request.

But I need to store only 45.78.

How to do it.

Any help appreciated.

Thanks,
gayatri
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66208
151
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Moved to Java in General (beginner).
 
Tom Sullivan
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here's one way but maybe not the best or only way.

 
Henry Wong
author
Sheriff
Posts: 23284
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you are using Java 5, and only want to print the result, take a look at the System.out.printf() method.

Otherwise, you can take a look at the DecimalFormat class.

Henry
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
[gayathri]:

I am getting 45.789887 as input from request.

But I need to store only 45.78.


Mmmm, are you sure 45.78 is what you want here? Not 45.79, which is much closer?

Depending on what you really want to do here, you may wish to add or subtract 0.005 to/from the number, to adjust the value to do the type of rounding you desire. You can experiment with different values to see how this works.
 
gayathri ramesh
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Say for example, I accept 47.898778 as the input. I dont want to round it off. I want to do a validation such that it accepts only two digits after decimal point. I want to know how to do validation for that.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How do you get input? From the console, a Swing gadget, a web page? We may be able to put constraints on the data entry to help the user. If not, we can try to validate the string after they enter it.
 
abhijit Ohal
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There must be some better way of doing this. any one have better ideas are appreciated
 
Mike Noel
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you're just trying to validate the format of the input then use a regular expression and pattern matching. If the format you want is <any number of digits>.<exactly two digits> then a regexp like this should work:

\d+.\d{2}

The Pattern.matches() static method will do what you want.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!