So in a CodeHS class I'm taking I'm trying to separate the cents from a balance of a bank account. Ex turn 12.34 to 34. I'm trying to use value.indexOf() and value.length() where value the balance. However, I keep getting "You may have forgotten to declare length() or it's out of scope" errors. I'm so confused because I thought these were built into Java itself but maybe not? I've already looked through the documentation but I'm still lost. Any help is appreciated.
Here's the code of the method (I think its a method idk the vocab lmao)
public class Currency
{
private Double value;
// Constructor
public Currency(Double startValue)
{
value = startValue;
}
// Sets value to newValue
public void setValue(Double newValue)
{
value = newValue;
}
// Returns the dollar portion of value
// if value is 12.34, returns 12
public Integer getDollars()
{
return (int)value.doubleValue();
}
// Returns the cents portion of value
// as an Integer
// if value is 12.34, returns 34
public Integer getCents()
{
return value.subSequence(value.indexOf("."), value.length());
}
// Returns a String representation
// in the format
// $12.34
public String toString()
{
return value.doubleValue();
}
}
As Commented by Jon Skeet, you are treating a Double
as if it is text. It is not text.
If you want text, make a String
object. Call Double#toString
. This method generates text to represent the value of the number held within the Double
object. The Double
object contains no text.
String s = myDouble.toString() ;
For a double
primitive, use the static
method Double.toString
.
double x = 42.7d ;
String s = Double.toString( x ) ;
String
offers the indexOf
and length
methods you seek.
By the way, in real work we never use double
/Double
types for money matters. Those floating-point types trade away accuracy for speed of execution.
For money matters, when accuracy is crucial, use the BigDecimal
class. Or, alternatively, multiply to get whole numbers as mentioned in another Comment.