Is there a way in JavaScript to format an array's output so that numbers are displayed with only two decimal places?

function calculateTipAmount(bill) {
  var tipPercent;
  if (bill < 50 ) {
    tipPercent = .20;

  } else if (bill >= 50 && bill < 200){
    tipPercent = .15;
  } else {
    tipPercent = .10;
  }

  return tipPercent * bill;
}

var bills = [124, 48, 268];
var tips = [calculateTipAmount(bills[0]),
            calculateTipAmount(bills[1]),
            calculateTipAmount(bills[2])];

var finalValues =[bills[0] + tips[0],
                 bills[1] + tips[1],
                 bills[2] + tips[2]];

console.log(tips, finalValues);

I am trying to format the result of 18.599999999999998 as $18.6 in the console. I attempted using .toFixed(2) but did not achieve the desired outcome.

Answer №1

toFixed() will give you a `string` output that needs to be converted back to a Number using Number().

function calculateTip(amount) {
var tipPercentage;
  if (amount < 50 ) {
    tipPercentage =  .20;

  } else if (amount >= 50 && amount < 200){
    tipPercentage = .15;
  } else {
    tipPercentage = .10;
  }

  return Number((tipPercentage * amount).toFixed(1));
}


var amounts = [124, 48, 268];
var tips = [calculateTip(amounts[0]),
              calculateTip(amounts[1]),
              calculateTip(amounts[2])];
var finalAmounts =[amounts[0] + tips[0],
                  amounts[1] + tips[1],
                  amounts[2] + tips[2]];
              
console.log(tips, finalAmounts);

Answer №2

In order to use the .toFixed() method, you must first ensure that the value of finalValues is a number. Convert it to a number before applying the method.

Try using console.log('$'+Number(finalValues).toFixed(2));

I trust this solution will be beneficial for you.

Answer №3

When it comes to rounding values, utilize .toFixed(1). This method is handy for formatting a number with a specific number of decimal places. Rather than directly returning the value using toFixed(), save the .toFixed() result in a variable before returning that variable.

function calculateTip(bill) {
var tipPercentage;
  if (bill < 50 ) {
    tipPercentage =  .20;

  } else if (bill >= 50 && bill < 200){
    tipPercentage = .15;
  } else {
    tipPercentage = .10;
  }
var calculatedTip=(tipPercentage * bill).toFixed(1);
  return parseFloat(calculatedTip);
}


  var bills = [124, 48, 268];
  var tips = ["$"+calculateTip(bills[0]),
              "$"+calculateTip(bills[1]),
              "$"+calculateTip(bills[2])];
  var finalValues =["$"+ bills[0] + tips[0],
                    "$"+bills[1] + tips[1],
                    "$"+bills[2] + tips[2]];
                  

  console.log(tips, finalValues);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilize Photoshop's Javascript feature to extract every layer within the currently active document

Looking for insights on a Photoshop scripting issue. I have written a solution but it's not producing the correct result. Can anyone provide feedback on what might be wrong with the code? The goal is to retrieve all the layers in a document. Here is ...

Strangely compressed HTML image

I am facing an issue with using a base64-encoded png retrieved from a server in WebGL. To incorporate the encoded png, I load it into an html Image object. For my specific needs, it is crucial that the png data remains completely lossless, however, I&apos ...

The Gusser Game does not refresh the page upon reaching Game Over

Hi there, I am a beginner in the world of JavaScript and currently working on developing a small guessing game app. However, I have encountered an issue where the page is not reloading after the game is over and the 'Play Again' button appears to ...

Adding a JSON array to HTML using JavaScript

Looking to incorporate JSON Array data into an HTML list with Headings/Subheadings using JavaScript. I experimented with two methods - one involving jQuery and the other mostly vanilla JS. The initial attempt (link here: http://jsfiddle.net/myu3jwcn/6/) b ...

The art of simulating a service in unit tests for an AngularAMD application

I am working on an angular application using AngularAMD with require.js. I need to simulate a service as shown below: module(function ($provide) { $provide.service('ToolsService', function () { var toolsServiceMock = { som ...

What is the best way to change a variable in an AngularJS view?

My Request In my application, I have implemented 3 views, each with its own controller. The first view is the home screen, and from there the user can navigate to view 2 by clicking on a div element. On view 2, the user can then move to view 3 by clicking ...

When the user clicks on an organizational chart, a new organizational chart will appear in a modal popup

Currently, I am developing a project with Highcharts where I have a specific requirement to display a modal popup when a node on an org chart is clicked. The popup should also contain another org chart. Below is the code snippet I am working with: [link to ...

What is a more efficient method for structuring this React page while making an asynchronous request to the API?

When developing, I encountered this scenario where I needed to ensure that a certain useEffect function only runs once. To achieve this, I established router.query.something as a dependency for the effect. The logic is such that the request will only trigg ...

Populate an HTML table using a JavaScript array containing objects

Greetings, fellow coders! I am new to the coding world and this community, and despite my efforts in searching for a solution, I couldn't find exactly what I was looking for. So, here is my question: I have an array structured as follows: const arr ...

Why does my window scroll change when making a $.ajax call?

Encountering a peculiar bug... Whenever my JS code enters the success function after a jQuery $.ajax call, the scroll position on my window suddenly jumps to the bottom of the page. This is problematic for me as I'm developing a mobile page and want t ...

Instructions for manipulating and displaying a source array from a child component using Vue

I have a parent component with an array that I display in the template. My goal is to click on a link that uses vue-router with a dynamic id attribute, and then open a new component displaying only the element of the array that corresponds to that id. Howe ...

Rails Navigation Issue: JQuery Confirmation Not Functioning Properly

Having a Rails app, I wanted to replicate the onunload effect to prompt before leaving changes. During my search, I came across Are You Sure?. After implementing it on a form, I noticed that it only works on page refreshes and not on links that take you a ...

JavaScript encounters an error when trying to create a MarkLogic instance with an array

[javascript] XDMP-CAST: (err:FORG0001) xs:string#1(.) -- Invalid cast: `json:object(<json:object xmlns:xs="http://www.w3.org/2001/XMLSchema" ` xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" .../>) cast as xs:string Stack Tr ...

Are you interested in using jQuery and/or AJAX to retrieve the latest images from a website?

I had to utilize a Wikipedia API in order to retrieve images from the New Jersey website, and I devised two methods to carry out similar tasks. The initial approach involved using JSON, but it ended up pulling the entire page content. <script type="tex ...

Problem with the getJSON function

Here is a question that has been bothering me: I am currently working on a barcode scanner script which retrieves data from a JSON file. The script itself functions properly, except for one issue. After the while loop, I want to display an error alert m ...

Freeze your browser with an Ajax request to a specific URL

There is a function in my view that transfers a value from a text box to a table on the page. This function updates the URL and calls another function called update_verified_phone(). The update_verified_phone() function uses a model called user_info_model( ...

Using Discord.js to retrieve identical lines from a text file in a database

I've been working on a discord bot that is supposed to send a line from a .txt file to the message author via DM, then delete that specific line from the file. However, it seems to be sending the same line repeatedly. Any suggestions on how to resolve ...

arrange items based on their category into arrays

I have a JSON file that needs to be arranged based on three specific fields. Here is an example snippet of the JSON data: { "Racename": "10KM", "Category": 34, "Gender": "Male", "Work": "Google", "FullName": "Dave Happner", "Rank": 1, "Poni ...

Tips for importing font files from the node_module directory (specifically otf files)

We cannot seem to retrieve the fonts file from the node module and are encountering this error message. Can't find 'assets/fonts/roman.woff2' in 'C:\Projects\GIT2\newbusinessapp\projects\newbusinessapp\src ...

Can a single controller function in ASP.NET MVC4 be used to send back two arrays to the view?

Continuing from my previous query here, I am working with a model called SchoolTestsPerModulePerStudent which looks like this: public partial class SchoolTestsPerModulePerStudent { public long StudentID { get; set; } public long ModuleID { get; se ...