0

I have a asp.net mvc application which displays data from a database table to a web page using knockout Js and Odata. In my model I have couple of entries which are Double type values and when I display them on a web page it works fine if the value is of type 2.05 but issue comes up when the value is of type 2 of 2.5 is that it just displays 2 and 2.5 instead I want it two decimal points like 2.00 and 2.50 respectively.

Model

public int Id { get; set; }
public double? Bid { get; set; }
public double? Offer { get; set; }

Knockout JS

self.getverticaldata = function () {
        $.ajax({
            dataType: "json",
            url: '/odata/CC',
            data: ko.toJSON(self.products),
            async: false,
            success: function (data) {
                self.datainput((ko.utils.arrayMap(data.value, function (canadiancrude) {
                    var obsCanadianCrude = {
                        Id: canadiancrude.Id,
                        Bid: ko.observable(canadiancrude.Bid),
                        Offer: ko.observable(canadiancrude.Offer),

                    }

                    return obsCanadianCrude;
                })));
            }
        });
    }

May I know a better way to deal with this and display the value upto two decimal values

DoIt
  • 3,270
  • 9
  • 51
  • 103

2 Answers2

1

in your binding, use toFixed

data-bind="text: Bid().toFixed(2)"
data-bind="text: Offer().toFixed(2)"

This will display 2.00 and 2.50.

Update

To deal with null and undefined, you can display empty string or some placeholder for it.

data-bind="text: (typeof Bid() === 'number') ? Bid().toFixed(2) : '' "
data-bind="text: (typeof Offer() === 'number') ? Offer().toFixed(2) : 'Not Exist!' "
huocp
  • 3,898
  • 1
  • 17
  • 29
0

You may want to have a look at the NumeralsJS library:

http://numeraljs.com/

And also this:

Javascript: Easier way to format numbers?

Community
  • 1
  • 1
uncoder
  • 1,818
  • 1
  • 17
  • 20