0

I get unexpected results in my currency converter. Here is the relevant code:

val = Float.parseFloat(values);

us=val*0.27f;
usa.setText(Float.toString(us));

pk=val=26.95f*val;
pak.setText(Float.toString(pk));

u=val*0.16f;
uk.setText(Float.toString(u));

om=val*0.10f;
oman.setText(Float.toString(om));

ks=val*1.02f;
ksa.setText(Float.toString(ks));

e=val*0.20f;
eu.setText(Float.toString(e)

I get:

us=0.27
e=0.2
uk=0.16
ksa=1.02
oman=2.69
pak=26.95

The oman-value is not correct. Why?

Huangism
  • 16,278
  • 7
  • 48
  • 74
  • 2
    what is `us` ,`pk` ,`val` datatypes ? – Suresh Atta Aug 14 '14 at 11:56
  • 2
    "I get unexpected results" - please provide a small compilable code example, the expected result and the actual result, so we can understand your problem. – LionC Aug 14 '14 at 11:57
  • please check now I have edited everything –  Aug 14 '14 at 12:05
  • All are float variables @sᴜʀᴇsʜᴀᴛᴛᴀ –  Aug 14 '14 at 12:05
  • @bsoftsolutions do not answer clarification questions in the comments - edit them into your question – LionC Aug 14 '14 at 12:09
  • ok @LionC ..and sorry am new here. –  Aug 14 '14 at 12:10
  • 1
    FYI: you might want to review [this question](http://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency) regarding the inadvisability of using floating-point numbers to represent currency values. – Adam Mackler Aug 14 '14 at 12:11

4 Answers4

3

Here:

pk=val=26.95f*val;

you overwrite val value. remove val= and it should work fine.

mata
  • 361
  • 3
  • 14
0

pk=val=26.95f*val; overwiting..

Talib
  • 1,134
  • 5
  • 31
  • 58
0

Do you know that the parameter type for Float.parseFloat is String?Actually the parseFloat method use for parse String to Float, But you said in the comment that all the variables are float!!

Babak-Na
  • 104
  • 1
  • 1
  • 8
0

Float, Double, float, double are not accurate in java. For example:

double number1 = 0.58 * 100;    
System.out.println("" + number1);

and the output is 57.99999999999999 not 58 as expected. BigDecimal class can be used instead for accurate performance.

  • This is true, but not the problem in the question at all – LionC Aug 14 '14 at 12:18
  • the problem was described as "Unexpected results", not actual numbers. And it is bad practice according to this http://www.javapractices.com/topic/TopicAction.do?Id=13 – Greta Radisauskaite Aug 14 '14 at 12:25
  • as I said, you are right about the problems with float point numbers and currency, but that was not the problem in the question and certainly not the cause of the unexpected results (it was already discovered to be the double assignment, in the accepted top rated answer). If you just want to point out bad practice, youre welcome to do it in the comments, but not as an answer – LionC Aug 14 '14 at 12:28