1

I need to create a simple calculator that computes 1% of the value submitted by the user. I also need to round it (floor) to the tenth part after colon.

Examples:

input    1%        output
12.34    0.1234    0.10
2345.34  23.4534   23.40

More info:
- users will submit monetary values. They can use dots or comma to separate the parts of the value. Both inputs 123.45 and 123,45 are valid.
- I need to calculate 1% of it, round it and display in "user friendly" form, for example XX.YY

I created following function so far. But it rounds the value in odd way. For example, for input "123.45" the output is 1.2000000000000002 (should be 1.20).

function calc(val)
{
var x = 0.1*Math.floor(0.1*val);
alert("your 1% is:\n"+x);
}

Javascript treats only values with dots as numbers. How can I easily convert values with commas to numbers?

And how to display the outcome with desired precision?

Gacek
  • 10,184
  • 9
  • 54
  • 87
  • Are users allowed to enter numbers with thousands/millions/etc separators? E.g. `1,234,567.89` and `1.234.567,89`? – Matt Ball Feb 11 '11 at 15:47
  • 1
    See [this](http://stackoverflow.com/questions/1074660/) and [this](http://stackoverflow.com/questions/2085275/) for info about working with different decimal separators. – Matt Ball Feb 11 '11 at 15:50
  • No, it is rather not expected. I really do not have to deal with thousand/etc separators. Thanks for the links! – Gacek Feb 11 '11 at 15:55

1 Answers1

4
val = parseFloat(val.toString().replace(",", ".")); // just replace comma with dot
var x = (0.1*Math.floor(0.1*val)).toFixed(2); // toFixed leaves required amount of digits after dicimal dot.
alert("your 1% is:\n"+x);
kirilloid
  • 14,011
  • 6
  • 38
  • 52