简体   繁体   中英

Java convert string to number, floating point only when needed?

I want to conver a string to number in Java. I already tried with two methods but both work bad with integers, adding an unneeded floating point: "1" > 1.0 (when I want "1" > 1 and "1.5" > 1.5). I found a couple more ways to convert strings to numbers but they either don't work or are many lines long, I cannot believe it's so complicated coming from javascript where I only need parseFloat().

This is what I'm trying now:

String numString = "1".trim().replaceAll(",","");
float num = (Float.valueOf(numString)).floatValue(); // First try
Double num2 = Double.parseDouble(numString); // Second try
System.out.println(num + " - " + num2); // returns 1.0 - 1.0

How can I have the floating point only when needed?

To format a float as you wish, use DecimalFormat :

DecimalFormat df = new DecimalFormat("#.###");
System.out.println(df.format(1.0f)); // prints 1
System.out.println(df.format(1.5f)); // prints 1.5

In your case, you could use

System.out.println(df.format(num) + " - " + df.format(num2));

I think what you're looking for is DecimalFormat

DecimalFormat format = new DecimalFormat("#.##");
double doubleFromTextField = Double.parseDouble(myField.getText());
System.out.println(format.format(doubleFromTextField));

The problem is with your question really in a type-safe language and I think you are mixing conversion and string representation. In Java or C# or C++ you convert to some predictable/expected type, looks like you expect the "Variant" behavior that you are used to in JavaScript.

What you could do in a type-safe language is this:

public static Object convert(String val)
{
  // try to convert to int and if u could then return Integer
  ELSE
  //try to convert to float and if you could then return it
  ELSE
  //try to convert to double
  etc...
}

Of course this is very inefficient just like JavaScript is compared to C++ or Java. Variants/polymorphism (using Object) comes at cost

Then you could do toString() to get integer formatted as integer, float as float and double as double polymorphically. But your question is ambiguous at best that leads me to believe that there is conceptual problem.

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