I've googled around a bit but could not find examples to find a solution. Here is my problem:
String s = "100.000";
long l = Long.parseLong(s);
The 2nd line of code which tries to parse the string 's' into a long throws a NumberFormatException.
Is there a way around this? the problem is the string representing the decimal number is actually time in milliseconds so I cannot cast it to int because I lose precision.
You could use a BigDecimal to handle the double parsing (without the risk of precision loss that you might get with Double.parseDouble()):
BigDecimal bd = new BigDecimal(s);
long value = bd.longValue();
as i don't know is your 100.000 equals 100 or 100 000
i think safest solution which i can recommend you will be:
NumberFormat nf = NumberFormat.getInstance();
Number number = nf.parse("100.000");
long l = number.longValue();
'long' is an integer type, so the String parse is rejected due to the decimal point. Selecting a more appropriate type may help, such as a double.
Just remove all spaceholders for the thousands, the dot...
s.replaceAll(".","");
You should use NumberFormat to parse the values
We can use regular expression to trim out the decimal part. Then use parseLong
Long.parseLong( data.replaceAll("\..*", ""));
If you don't want to loose presision then you should use multiplication
BigDecimal bigDecimal = new BigDecimal("100.111");
long l = (long) (bigDecimal.doubleValue() * 1000);<--Multiply by 1000 as it
is miliseconds
System.out.println(l);
Output:
100111
Related
I'm trying to show milliseconds as seconds while also keeping the decimals e.g. I have 1234 milliseconds and I want to show this as 1.234 seconds.
Decimal duration = 1234;
NumberFormat formatter = new DecimalFormat("#0.000");
String durationStr = formatter.format(duration / 1000);
Any suggestions how I could do this?
It sounds like you should be using BigDecimal - create a BigDecimal from the long, and then scale it by 3 places:
BigDecimal bd = new BigDecimal(duration).scaleByPowerOfTen(-3);
String durationStr = formatter.format(bd);
By using BigDecimal instead of double, you know that you'll still have exactly the value you're really considering, rather than simply "the nearest approximation that double can hold".
You may well also want:
formatter.setMinimumFractionDigits(3);
formatter.setMaximumFractionDigits(3);
... to ensure that you always get exactly 5 digits. (Assuming you want 1 second to be "1.000" for example.)
Use a double to divide the number 1000d.
String durationStr = formatter.format(duration / 1000d);
I got the following BigDecimal from a Money-Object: BigDecimal 49.99 and I need this as Integer 4999, so everything I ask for is getting rid of the separator.
I could get this BigDecimal as String and remove the separator and parse it to an Integer, but I do not think that this is pretty.
BigDecimal bigPrice = moneyPrice.getValue();
Integer price = bigPrice.intValue();
Using this only responses with 49.
You need the method:
movePointRight(int n)
javadoc link: http://docs.oracle.com/javase/6/docs/api/java/math/BigDecimal.html#movePointRight(int)
example:
BigDecimal bd = new BigDecimal("398.0275");
System.out.println(bd.movePointRight(bd.scale()));
outputs:
3980275
If you want to use the number, just bd=bd.movePointRight(bd.scale());
Try this code:
BigDecimal db = new BigDecimal("49.99");
// multiply with 10^scale ( in your case 2)
db = db.multiply(new BigDecimal(10).pow( db.scale()));
System.out.println(db.intValue());
If it's currency and always to 2 dp, you could multiple it by 100. However as Davio comments, your code should make it clear why you're doing it.
If you want to convert, for example a price in GB pounds sterling to GB pence (100 pence in a pound) then multiplying it by 100 is the right thing to do.
It's not necessary to do any math on the BigDecimal; you can just call myBigDecimal.unscaledValue() to get the underlying unscaled BigInteger directly.
I have following sample (link to ideone).
long lDurationMillis = 0;
lDurationMillis = Long.parseLong("30000.1");
System.out.print("Play Duration:" + lDurationMillis);
It throws an exception:
Exception in thread "main" java.lang.NumberFormatException: For input string: "30000.1"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Long.parseLong(Long.java:419)
at java.lang.Long.parseLong(Long.java:468)
at Main.main(Main.java:9)
But why it wont let me convert that number to a string directly ?I can convert number to integer and than convert to double . But is there any other way ?
The value 30000.1 is an invalid long value. You could parse the double value first:
lDurationMillis = (long)Double.parseDouble("30000.1");
You could use BigDecimal in this case:
BigDecimal bd = new BigDecimal("30000.1");
long l = bd.setScale(0, BigDecimal.ROUND_HALF_UP).longValue();
System.out.println(l);
The title says converting string to long, first question is about coverting number to string, next statement about converting number to integer to string. I am confuse.
But for anything to do with floating points, I have to point you at obligatory reference What Every Computer Scientist Should Know About Floating-Point Arithmetic .
In java, int and long do not have fractional parts, so a string like 3000.1 cannot be covnerted to one of these. It can be converted to float or double but if you read the above article you will realize that the coversion can be lossy, i.e. if you canvert that double back to a String you may not get the original 3000.1 back. It will be something close, for appropriate defintion of close, but may not be same.
If you want to use exact precision then BigDecimal is your friend. It will be much slower then the number types, but it will be precise.
Because long can't have fractional part, you could convert it to double and then cast it to long ignoring fractional part
You can do NumberFormat handling as below :
long lDurationMillis = 0;
try{
NumberFormat nf = NumberFormat.getInstance();
lDurationMillis = nf.parse("30000.1").longValue();
System.out.print("Play Duration:" + lDurationMillis);
}catch(ParseException e)
{
e.printStackTrace();
}
Output:
Play Duration:30000
Is there a way to execute a piece of code depending on how many decimal places there are in a number. For instance, if the double was just 2.0 i would want to convert it to an integer, but if it were 2.43426 i would want to leave it as a double. Thanks!
Not sure, but would:
double d = 2.0;
if ((long) d == d) {
// then
}
Work for you? That only answers your question in that particular case.
You can specify precision and convert like this:
double precision = 1e-10;
int rounded = Math.round(x);
if (Math.abs(x-rounded) > precision) System.out.print(x)
else System.out.print(rounded);
Convert the double to String
Using regex, find the decimal point and then get the number of characters after that.
Use it in your if-else
A quick and dirty solution would be the following:
double foo = 2.43426;
int count = String.valueOf(foo).split(".")[1].toCharArray().length;
if(count > 1){
// do stuff
}
If this is what you're after:
i would be converting them to strings and writing them out, so i would want it to say 3 instead of 3.0, but not 3 instead of 3.4324.
Then the "correct" way is using DecimalFormat:
DecimalFormat fmt = new DecimalFormat("0.#");
fmt.setMaximumFractionDigits(Integer.MAX_VALUE);
assert "3".equals(fmt.format(3.0));
assert "3.4324".equals(fmt.format(3.4324));
It does, however, localize the decimal separator (I get a comma rather than a dot). If that's an issue, you can just call fmt.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.ROOT)).
I have a very small number and I want to convert it to a String with the full number, not abbreviated in any way. I don't know how small this number can be.
for example, when I run:
double d = 1E-10;
System.out.println(d);
it shows 1.0E-10 instead of 0.000000001.
I've already tried NumberFormat.getNumberInstance() but it formats to 0. and I don't know what expression to use on a DecimalFormat to work with any number.
Assuming that you want 500 zeroes in front of your number when you do:
double d = 1E-500;
then you can use:
double d = 1E-10;
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(Integer.MAX_VALUE);
System.out.println(nf.format(d));
You can set the maximum and minimum number of digits in the fraction of a numberformatter with setMinimumFractionDigits and setMaximumFractionDigits. that should fix the problem.
You can do it with BigDecimals in Java 5 using:
System.out.println(new java.math.BigDecimal(Double.toString(1E-10)).stripTrailingZeros().toPlainString());
Note that if you have the double value as a String in the first place, you would be better off using:
System.out.println(new java.math.BigDecimal("1E-10").toPlainString());
... as explained in the BigDecimal javadocs.
Have a look at: http://java.sun.com/docs/books/tutorial/i18n/format/decimalFormat.html#numberpattern
I think the format "0.####" might work.