Gacek
Gacek

Reputation: 10322

Simple data validation and math operation in JavaScript

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?

Upvotes: 1

Views: 589

Answers (1)

kirilloid
kirilloid

Reputation: 14304

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);

Upvotes: 4

Related Questions