I have a string like 46542.5435657468
, but i want format this string and need only two charector after dot "." like 46542.54
. Please suggest me which String method i need to use.
Asked
Active
Viewed 2,523 times
0

mvts himm
- 117
- 1
- 4
- 16
-
possible duplicate of [Round a double to 2 significant figures after decimal point](http://stackoverflow.com/questions/2808535/round-a-double-to-2-significant-figures-after-decimal-point) – Pankaj Kumar Sep 12 '13 at 12:22
5 Answers
3
You can use DecimalFormat
first declare this at the top
DecimalFormat dtime = new DecimalFormat("#.##"); //change .## for whatever numbers after decimal you may like.
then use it like this
dtime.format(your string);
like:
String a = "46542.5435657468";
dtime.format(a);
output will be 46542.54

Ahmed Ekri
- 4,601
- 3
- 23
- 42
-
http://stackoverflow.com/questions/2808535/round-a-double-to-2-significant-figures-after-decimal-point – Pankaj Kumar Sep 12 '13 at 12:23
-
-
I didn't said that you are wrong :) your answer is perfect. I just indicating that this question has been answered tooooo many times .. :) – Pankaj Kumar Sep 12 '13 at 12:26
1
You can use a method like this.
private static String extract(String text) {
String[] values = text.split(".");
return values[0] + "." + values[1].substring(0, 2);
}

Yuichi Araki
- 3,438
- 1
- 19
- 24
0
The method indexOf tell you the position of the character "." ok?
The method substring cut a peace of the string from the begining (value 0) until the positio of the character "." plus 2 digits more.
public String getNumberFormated(String yourNumber)
{
return yourNumber.substring(0, yourNumber.indexOf(".") + 2);
}
Do you like my solution?

Juan Pedro Martinez
- 1,924
- 1
- 15
- 24