I know I can parse from Long from String like the following
"60".toLong
or convert Long from Double like the following
60.0.toLong
or convert Long from a String of Double like the following
"60.0".toDouble.toLong
However, I can't do the following
"60.0".toLong
So my question is whether using .toDouble.toLong is a best practice, or should I use something like try ... catch ...?
Meanwhile, there is another question, when I try to convert a very large Long to Double, there maybe some precision loss, I want to know how to fix that?
"9223372036854775800.31415926535827932".toDouble.toLong
You should wrap the operation in a Try anyway, in case the string is not valid.
What you do inside the Try depends on whether "60.0" is a valid value in your application.
If it is valid, use the two-step conversion.
Try("60.0".toDouble.toLong) // => Success(60)
If it is not valid, use the one-step version.
Try("60.0".toLong) // => Failure(java.lang.NumberFormatException...)
Answer to updated question:
9223372036854775800.31415926535827932 is outside the range for a Double, so you need BigDecimal for that.
Try(BigDecimal("9223372036854775800.31415926535827932").toLong)
However you are very close to maximum value for Long, so if the numbers really are that large I suggest avoiding Long and using BigDecimal and BigInt.
Try(BigDecimal("9223372036854775800.31415926535827932").toBigInt)
Note that toLong will not fail if the BigDecimal is too large, it just gives the wrong value.
Related
On scala my BigDecimal is 3.721443204405954385563870541379242E+54
I would like to result to 3721443204405954385563870541379246659709506697378694300
My result is:
3.114968783111033211375362915188093E+41
I would like to result to be:
311496878311103321137536291518809134027240
I do not know the scale and the result should be only show the integer part.
val multimes:(Int, Int)=>BigDecimal=(c:Int, begin:Int)=>{
if(c==1)
BigDecimal.apply(begin)
else
multimes(c-1, begin)*(c+begin-1)
}
def mulCount(c:Int):BigDecimal={
val upper=multimes(c,c+1)
val down=multimes(c,2)
upper/down
}
the number is the result of function mulCount.
The BigDecimal class has a number of nonintuitive behaviors in Scala 2.10. This will get better in 2.11, but I can't quite tell from your example whether it will fix what you want. Probably not; Scala has a default MathContext which keeps about 128 bits of information (~34 decimal digits), and I think that's what you're running into here.
If you don't have a decimal problem--and here you don't--then the easiest thing to do is just use BigInt instead. It will scale to however many digits you actually need.
If you must express this as a decimal problem, you should explicitly supply a MathContext that has enough digits:
if (c==1) BigDecimal.apply(begin, new java.math.MathContext(60))
and that MathContext will, if always used on the left-hand side of operations, propagate through to your result.
It sounds as though you're mostly concerned about the appearance of the number, and don't want to see it in scientific notation with the exponent.
This is default behaviour for just printing a BigDecimal and can't be overridden. But you can explicitly convert it to a String before printing.
This should do the trick:
val bd: BigDecimal = ...
println(bd.bigDecimal.toPlainString)
That said... Why not just use BigInt?
Using strings as String objects is pretty convenient for many string processing tasks.
I need extract some substrings to process and scala String class provide me with such functionality. But it is rather expensive: new String object is created every time substring function is used. Using tuples (string : String, start : Int, stop : Int) solves the performance problem, but makes code much complicated.
Is there any library for creating string proxys, that stores original string, range bound and is compatibles with other string functions?
Java 7u6 and later now implement #substring as a copy, not a view, making this answer obsolete.
If you're running your Scala program on the Sun/Oracle JVM, you shouldn't need to perform this optimization, because java.lang.String already does it for you.
A string is stored as a reference to a char array, together with an offset and a length. Substrings share the same underlying array, but with a different offset and/or length.
Look at the implementation of String (in particular substring(int beginIndex, int endIndex)): it's already represented as you wish.
I am using the pow() function like this in my application:
float IValuePlusOne = (pow(2.25,120));
but it is reporting back an infinite value, instead of the correct result. I even tried the long long and long double data types but couldn't get them to produce the proper output.
Is there any other data type I need to use or do I need to make some other changes in my code?
As others have pointed out, you're losing precision and reducing the size of value you can represent by casting to a float. Running the following code:
double IValuePlusOne = pow(2.25,120.0);
NSLog(#"Test value: %f", IValuePlusOne);
on my iPhone gives the output:
Test value: 1827688475348373523156051712429585892114432.000000
which looks to be correct (1.827x10^42).
If you want to do calculations on values that a double can't hold, use NSDecimalNumber.
I need to print a formatted string containing scala.Long.
java.lang.String.format() is incompatible with scala.Long (compile time) and RichLong (java.util.IllegalFormatConversionException)
Compiler warns about deprecation of Integer on the following working code:
val number:Long = 3243
String.format("%d", new java.lang.Long(number))
Should I change fomatter, data type or something else?
You can try something like:
val number: Long = 3243
"%d".format(number)
The format method in Scala exists directly on instances of String, so you don't need/want the static class method. You also don't need to manually box the long primitive, let the compiler take care of all that for you!
String.format("%d", new java.lang.Integer(number))
is therefore better written as
"%d".format(number)
#Bruno's answer is what you should use in most cases.
If you must use a Java method to do the formatting, use
String.format("%d",number.asInstanceOf[AnyRef])
which will box the Long nicely for Java.
Suppose I wish to have 2 functions, one that generates a random integer within a given range, and one that generates a random double within a given range.
int GetRandomNumber( int min, int max );
double GetRandomNumber( double min, double max );
Notice that the method names are the same. I'm trying to decide whether to name the functions that or...
int GetRandomInteger( int min, int max );
double GetRandomDouble( double min, double max );
The first option has the benefit of the user not having to worry about which one they are calling. They can just call GetRandomNumber with integers or doubles and get a result.
The second option is more explicit in the names, but it reveals unneeded information to the caller.
I know this is petty, but I care about petty things.
Edit: How would C++ behave regarding implicit conversion.
Example:
GetRandomNumber( 1, 1 );
This could be implicitly converted for the GetRandomNumber function for the double version. Obviously I don't want this to occur. Will C++ use the int version before the double version?
I prefer your second example, it is explicit and leaves no ambiguity in interpretation. It is better to err on the side of being explicit in method names to clearly illuminate the purpose and function of that member.
The only downside to your approach is that you have coupled the name of the method to the return type which is not ideal in the event that you want to change the return type of one of these methods. However in that case I would be better to add a new method and not break compatibility in your API anyways.
I prefer the second version. I like overloading a function when ultimately the two functions do the same thing; in this case they return different types so they're not quite the same thing. Another possibility if your language supports it is to define it as a generic/template method, like:
T GetRandom<T>(T min, T max);
A function name should tell what the function does; I do not see a point in cramming the types into the names. So definitely go for overloading - that's what it is for.
I prefer the overloaded method. Look at the Math.Min() method in .NET. It has 11 overloads: int, double, byte, etc.
I usually prefer the first example because it doesn't pollute the namespace. For example when calling it, if I pass ints, I'm expecting to get back an int. If I pass in doubles, I probably expect to get back a double. The compiler will give you an error if you write:
//this causes an error
double d = GetRandomNumber(1,10);
so it's not really a big issue. and you can always cast the arguments if you need an int but have doubles for input...
In some of languages you can not vary the return type of overloaded functions this would require the second example.
Assuming C++, the second also avoids problems with ambiguity. If you said:
GetRandomNumber( 1, 5.0 );
which one should be used? In fact, it is a compilation error.
I think the ideal solution would be
Int32.GetRandom(int min, int max)
Double.GetRandom(double min, double max)
but, alas, static extension method are not possible (yet?).
The .net Framwork seems to favor the first option (System.Math class):
public static decimal Abs(decimal value)
public static int Abs(int value)
Like Andrew, I would personally favor the second option to avoid ambiguity, although I do think this is a matter of taste.