开发者

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:

开发者_JAVA百科- 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?


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜