简体   繁体   English

Java将字符串转换为数字,仅在需要时浮点数?

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

I want to conver a string to number in Java. 我想在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). 我已经尝试过两种方法,但两种方法都不正常,添加了一个不需要的浮点:“1”> 1.0(当我想要“1”> 1和“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(). 我找到了几种将字符串转换为数字的方法,但是它们要么不起作用,要么很多行,我不敢相信它来自javascript,我只需要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 : 要根据需要格式化float,请使用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

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. 在Java或C#或C ++中,您可以转换为某种可预测/期望的类型,看起来您期望在JavaScript中习惯使用“Variant”行为。

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. 当然,就像JavaScript与C ++或Java相比,这是非常低效的。 Variants/polymorphism (using Object) comes at cost 变体/多态(使用Object)需要付出代价

Then you could do toString() to get integer formatted as integer, float as float and double as double polymorphically. 然后你可以使用toString()来获取整数格式为整数,浮点数为float,double为double多态。 But your question is ambiguous at best that leads me to believe that there is conceptual problem. 但是你的问题充其量是模棱两可的,这使我相信存在概念问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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