简体   繁体   中英

Simple and clean java float to string conversion

This is a very simple question, but I'm amazed on how difficult it has been to answer. Even the documentation didn't give a clear and straight answer.

You see, I'm simply trying to convert a simple float to a string such that the result only has one decimal digit. For example:

String myfloatstring = "";
float myfloat = 33.33;
myfloatstring = Float.toString(myfloat);

This does indeed return "33.33". This is fine, except I'm looking for a way to get it to truncate the decimal to "33.3". It also needs to impose a decimal whenever a whole number is put in. If myfloat was 10, for example, it would need to display as "10.0". Oddly not as simple as it sounds.

Any advice you can give me would be greatly appreciated.

EDIT #1:

For the moment, I'm not concerned with digits to the left of the decimal point.

System.out.println(String.format("%.1g%n", 0.9425));
System.out.println(String.format("%.1g%n", 0.9525));
System.out.println(String.format( "%.1f", 10.9125));

returns:

0.9
1
10.9

Use the third example for your case

Stupid roundabout way of doing it:

float myFloat = 33.33f;
int tenTimesFloat = (int) (myFloat * 10); // 333
String result = (tenTimesFloat / 10) + "." + (tenTimesFloat % 10); // 33.3

Note that this truncates the number, so 10.99 would convert to 10.9 . To round, use Math.round(myFloat * 10) instead of (int) (myFloat * 10) . Also, this only works for float values that are between Integer.MAX_VALUE/10 and Integer.MIN_VALUE/10 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM