2

I am using mvc3 with c# language where I was stuck in calculation problem.Here I am using double type variables for 3 properties Qty,Cost and totalprice

Here totalprice=Qty*Cost;

I have requirement where I want to get totalprice of product without decimals. For example if qty=14.3 , cost=15. Then on java script/C# I will get total price 214.5

But I require 214.To solve this I used Math.Floor(214.5) to get 214. But when Qty=18.9 and cost=1500. Then on javascript or C# multiplication, I am getting total price=28349.999999999996, The correct result should be 28350. Please help me to get solution where I will get both result accurately

user1513684
  • 105
  • 1
  • 11
  • 3
    You can use `Math.round(totalprice - .1)` to get the price rounded to the nearest integer with a preference for the floor value (employing - 0.1) – Polity Mar 11 '13 at 06:44

3 Answers3

2

Choose according to you in c#.

-3        -2        -1         0         1         2         3
 +--|------+---------+----|----+--|------+----|----+-------|-+
    a                     b       c           d            e

                       a=-2.7  b=-0.5  c=0.3  d=1.5  e=2.8
                       ======  ======  =====  =====  =====
Floor                    -3      -1      0      1      2
Ceiling                  -2       0      1      2      3
Truncate                 -2       0      0      1      2
Round (ToEven)           -3       0      0      2      3
Round (AwayFromZero)     -3      -1      0      2      3

In javscript do like this:

var qty=qty.toFixed(1);
var cost=cost.toFixed(1);
var totalprice=Math.round(qty*cost);
Amrendra
  • 2,019
  • 2
  • 18
  • 36
1

you can use Math.round(); this solves your problem.

Math.round(214.5- .1);
PSR
  • 39,804
  • 41
  • 111
  • 151
1

This question already has an answer here: Javascript floating calculation error

you can use toFixed() for example: (1.2 - 1).toFixed(1) * 1 // 0.2

Community
  • 1
  • 1
Mehdi Emrani
  • 1,313
  • 2
  • 14
  • 26