Javascript-toFixed()0.5问题

时间:2019-06-06 10:29:19

标签: javascript

我有一种情况,我想将小数点后两位小数舍入。 目前.toFixed(2)可以正常工作,但是对于0.455,我想得到0.45,而不是0.46

对此有任何快速解决方案吗?如果可以解决此问题,我可以使用Lodash。

例如,我想要以下内容。

0.455> 0.45

0.456> 0.46

0.4549> 0.45

2 个答案:

答案 0 :(得分:2)

乘以100,向下取整,向下除以100,格式为toFixed。

Carthage version 0.33.0
carthage bootstrap --no-build --platform ios

一个更通用的版本是

function draw_d3_piechart(input_data){
  // putting the datapoints in an array
  var data = {math: input_data["VALUE_MATH"], reading: 
     input_data["VALUE_READ"], science:input_data["VALUE_SCIENCE"]};

  console.log(data);
  // the output of this is :
  // {math: 387, reading: 398, science: 397}

  // determining the width, height
  var margin = {top: 50, right: 100, bottom: 0, left: 50},
    svgWidth = 500,
    svgHeight = 400,
    plotWidth = width - margin.left - margin.right,
    plotHeight = height - margin.top - margin.bottom,
    radius = Math.min(svgWidth, svgHeight) / 2;


  // creating svg element in a div that is in the html file
  var svg = d3.select("#piechart_area"),
        width = svgWidth,
        height = svgHeight;

  // creating g element for the chart to be written in
  var g = svg.append("g")
            .attr("transform", "translate(" + svgWidth / 2 + "," + 
                   svgHeight / 2 + ")");

  // creating colorscale
  var color = d3.scaleOrdinal()
              .domain(data)
              .range(["#98abc5", "#8a89a6", "#7b6888"]);

  // determining size of wedges
  var pie = d3.pie()
            .sort(null)
            .value(function(d) {return d.value; });
  var data_ready = pie(d3.entries(data));

  g
  .selectAll('g')
  .data(data_ready)
  .enter()
  .append('path')
  .attr('d', d3.arc()
    .innerRadius(0)
    .outerRadius(radius)
  )
  .attr('fill', function(d){ return(color(d.data.key)) })
  .attr("stroke", "black")
  .style("stroke-width", "2px")
  .style("opacity", 0.7);


};

答案 1 :(得分:0)

这应该有帮助:

function roundDecimal(a, k) {
  let K = Math.pow(10, k);
  return Math.round(a * K) / K;
}

所以roundDecimal(0.455, 2)将是0.46