0

How to Store a float Value with 1 decimal point as a float value in java. for (e.g), I'm using the following code to limit the float value to 1 digit after decimal point but as a string so again converted it to float. But, after the conversion receiving a long float value like (value = 2.39725527E11) i need it to be like (value = 2.3) and store it in a float variable as 2.3 not 2.39725527E11

float_str = String.format("%.1f", value);
value = Float.parseFloat(float_str);  
System.out.println("value = " + value);
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
Lingaraj
  • 99
  • 2
  • 13
  • 2
    You can''t get there from here. Read [the tag wiki](https://stackoverflow.com/tags/floating-point/info). `2.3` [can't be stored in a float variable](https://ideone.com/OyPaf1). – Eric Dec 17 '15 at 06:54
  • 2
    You know 2.39725527E11 is a very _large_ number? It's 239725527000. Additionally, float numbers are _always_ going to be binary fractions; they don't have a specific number of decimal digits like 1. – Louis Wasserman Dec 17 '15 at 06:55
  • 1
    As remarked by others, when you try limit a float to a specific format, float value doesn't remain an actual Java "float" type. I think , this link has quite a few suggestions but your end output will not remain Java "float" type. [Format Float to n decimal places](http://stackoverflow.com/questions/5195837/format-float-to-n-decimal-places) – Sabir Khan Dec 17 '15 at 07:04

2 Answers2

3

You could use a BigDecimal. Something like,

BigDecimal bd = BigDecimal.valueOf(2.39725527E11f);
bd = bd.setScale(1, RoundingMode.HALF_UP);
System.out.println("value = " + bd);

I get

value = 239725527040.0

Alternatively, removing the exponent and then rounding can give you something like

float f = 2.39725527E11f;
f /= Math.pow(10, (int) Math.log10(f));
f = ((int) (f * 10)) / 10.0f; // <-- performs one digit floor
System.out.println("value = " + f);

And I get

value = 2.3
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

If you already have the float as a string I believe this would work...

String floatstr = ""; // Create a variable to assign string values too
for (int i = 0; i < float_str.length(); i++) // Loop through the character array in the string.
    floatstr += float_str.charAt(i); // add the current value to floatstr
    if (float_str.charAt(i) == '.' && i != float_str.length() - 1) // If there is a dot, and it isn't the last character
    {
        floatstr += float_str.charAt(i + 1); // add the next character to it
        break; // break so it doesn't take in any more characters
    }
float_str = floatstr; // Assign the string with one variable next to dot back into original string.
Riley Carney
  • 804
  • 5
  • 18